我没有得到正确的解决方案,如何从单击的 SwiftUI 按钮打开 UIKit ViewController(带导航 Controller )。
最佳答案
您可以使用 UIViewControllerRepresentable
协议(protocol)来完成此操作,该协议(protocol)用于在 SwiftUI
中管理 UIKit ViewController
。
这里是从 SwiftUI View 界面显示 ViewController
的代码。
SwiftUI View
struct ContentView: View {
@State var isOpenView = false
var body: some View {
NavigationView {
VStack {
//show your view controller
NavigationLink(destination: TestControllerView(), isActive: $isOpenView) {
EmptyView()
}
Button(action: {
self.isOpenView = true
}){
Text("Tap Me")
}
}
}
}
}
现在将您的 ViewController 包装到 UIViewControllerRepresentable
struct TestControllerView : UIViewControllerRepresentable {
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
func makeUIViewController(context: Context) -> some UIViewController {
guard let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "TestViewController") as? TestViewController else {
fatalError("ViewController not implemented in storyboard")
}
return viewController
}
}
这是您的 ViewController.Swift 文件代码
import UIKit
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func btnBackClicked(_ sender : UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
关于swiftui - 从 SwiftUI 打开 UIKit ViewController 的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72614674/