ios - 将 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
提前感谢大家的帮助!
解决方案
基本策略是使用 aView
代表您要从 a 引入的内容UIViewController
。您View
将遵守UIViewCotrollerRepresentable
并使用该协议的功能来创建和管理UIKit
内容。
UIViewControllerRepresentable
文档在这里
而且,正如 vadian 在您的原始帖子中所评论的那样,有一个带有示例代码的教程
使用上面的示例代码,我会将“ViewController”重命名为类似PassBaseViewController
or 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*/
}
}
推荐阅读
- c# - 当用户将鼠标悬停在 TreeView 控件的特定 TreeNode 控件上时显示不同的光标
- javascript - AZURE 文件服务 - 通过 REST API 上传 PDF
- php - Laravel firstOrNew 按特定表列
- mysql - 将金额分类的案例语句
- ios - 这段 Swift 代码在做什么?func somefunc(其中:(_:NSLayoutConstraint)-> Bool)
- java - 接口关闭时如何在Java中读取网络接口静态IP
- java - 是否可以使用这些接口作为参数创建方法?
- python - 如何在 matplotlib 中连接两个不同大小的图形?
- ios - 从 xcassets 加载图像会导致断言失败
- javascript - 如何使用 JavaScript 在页面底部添加空白?