【问题标题】:Inserting UIKit content into a SwiftUI view hierarchy将 UIKit 内容插入 SwiftUI 视图层次结构
【发布时间】:2021-10-28 15:43:39
【问题描述】:

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

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

提前感谢大家的帮助!

【问题讨论】:

标签: ios swift xcode swiftui


【解决方案1】:

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

UIViewControllerRepresentable 文档是 here

而且,正如 vadian 在您的原始帖子中所评论的那样,有 A tutorial with sample code

使用上面的示例代码,我会将“ViewController”重命名为PassBaseViewControllerPBViewController,然后您将创建一个派生自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*/
    }
}

【讨论】:

  • 您好!感谢你的回答!在 Apples 网站上的示例中提供的功能中,我是否只导入整个 UIKit 类?很抱歉造成混乱,我对 UIKit 的工作原理一无所知。 ://
  • 让我更详细地编辑答案
  • 谢谢!就像您发布编辑一样,我做了完全相同的事情!我遇到了一个问题,当我想在视图中包含此按钮时,它不可点击,我实现它的唯一方法是使用导航链接到视图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多