首页 > 解决方案 > 将 UIKit 内容插入 SwiftUI 视图层次结构

问题描述

对不起,如果标题令人困惑,我对整个事情有点陌生。

我正在尝试将 PassBase ID 验证集成到我的应用程序中,该应用程序是使用 SwiftUI 构建的,他们的文档提供了使用 Swift 和视图控制器的说明。我的问题是,有没有办法将 Swift 代码部分插入到我的 SwiftUI 视图中?

他们文档中的代码示例:

import Passbase
import UIKit
class ViewController: UIViewController, PassbaseDelegate {
override func viewDidLoad() {
    super.viewDidLoad()
    PassbaseSDK.delegate = self
    // Optional - You can prefill the email to skip that step.
    Passbase.prefillUserEmail = "testuser@yourproject.com"
    let button = PassbaseButton(frame: CGRect(x: 40, y: 90, width: 300, height: 60))
    self.view.addSubview(button)
}

func onFinish(identityAccessKey: String) {
  print("onFinish with identityAccessKey \(identityAccessKey)")
}

func onSubmitted(identityAccessKey: String) {
  print("onSubmitted with identityAccessKey \(identityAccessKey)")
}

func onError(errorCode: String) {
  print("onError with code \(errorCode)")
}

func onStart() {
  print("onStart")
}
}

据我了解,这部分代码应该在 VC 中创建一个按钮。我的目标是将此按钮与功能添加到我的 SwiftUI 视图中。

完整文档:https ://docs.passbase.com/ios#general

提前感谢大家的帮助!

标签: iosswiftxcodeswiftui

解决方案


基本策略是使用 aView代表您要从 a 引入的内容UIViewController。您View将遵守UIViewCotrollerRepresentable并使用该协议的功能来创建和管理UIKit内容。

UIViewControllerRepresentable文档这里

而且,正如 vadian 在您的原始帖子中所评论的那样,有一个带有示例代码的教程

使用上面的示例代码,我会将“ViewController”重命名为类似PassBaseViewControlleror PBViewController,然后您将创建一个View派生自UIViewControllerRepresentable

您最终会得到一个名为 PBViewController.swift 的文件,其中包含您的代码:

import Passbase
import UIKit

class PBViewController: UIViewController, PassbaseDelegate {
override func viewDidLoad() {
    super.viewDidLoad()
    PassbaseSDK.delegate = self
    // Optional - You can prefill the email to skip that step.
    Passbase.prefillUserEmail = "testuser@yourproject.com"
    let button = PassbaseButton(frame: CGRect(x: 40, y: 90, width: 300, height: 60))
    self.view.addSubview(button)
}

... and the rest of the code from your question here ...

然后(可能在另一个文件中,但不一定)您可以创建使用该视图控制器的 SwiftUIView:

struct PassBaseView : UIViewControllerRepresentable {
    typealias UIViewControllerType = PBViewController

    func makeUIViewController(context: Context) -> PBViewController {
        return PBViewController()
    }

    func updateUIViewController(_ uiViewController: PBViewController, context: Context) {
        /* code here to make changes to the view controller if necessary when this view is updated*/
    }
}

推荐阅读