繁体   English   中英

将 UIKit 内容插入 SwiftUI 视图层次结构

[英]Inserting UIKit content into a SwiftUI view hierarchy

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

我正在尝试将 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

在此先感谢大家的帮助!

基本策略是使用一个View来表示您要从UIViewController引入的内容。 您的View将符合UIViewCotrollerRepresentable并使用该协议的功能来创建和管理UIKit内容。

UIViewControllerRepresentable文档在这里

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

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

您最终会得到一个名为 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*/
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM