![](/img/trans.png)
[英]Assign @state var from SwiftUIView in UIViewController
[英]Navigate to a UIViewController from inside a SwiftUIView
我有一个UIKit
应用程序,其中我有一个SwiftUIView
托管在UIHostingController
中,在这个 SwiftUIView 中,我有一个Button
,我想在点击时导航到另一个UIViewController
。
如何从 SwiftUIView 中导航到UIViewController
?
struct SwiftUIView: View {
var body: some View {
Button(action: {
// on tap, go to MyViewController
}) {
Text("Go to UIViewController")
}
}
}
谢谢
编辑:显示Kyokook Hwang
的代码(选项一)。
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myLabel = UILabel(frame: CGRect(x: 100, y: 100, width: 200, height: 21))
myLabel.text = "My Label"
view.addSubview(myLabel)
}
}
import SwiftUI
struct MyView: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<MyView>) -> MyViewController {
let vc = MyViewController()
return vc
}
func updateUIViewController(_ uiViewController: MyViewController, context: UIViewControllerRepresentableContext<MyView>) {
}
}
struct SomeView: View {
@State var isShowingMyVC = false
var body: some View {
VStack{
Button(action: {
self.isShowingMyVC = true
}) {
Text("Go to UIViewController")
.sheet(isPresented: $isShowingMyVC) {
MyView()
}
}
}
}
}
据我所知,有两种方法可以实现您想要做的事情。
1.使用UIViewControllerRepresentable
。
1) 使用包含您想要呈现的 UIViewController 的协议创建一个桥视图。
2) 使用.sheet
运算符在按钮被触摸时呈现桥视图。
下面有一个例子。
struct MyView: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<MyView>) -> MyViewController {
let vc = MyViewController()
return vc
}
func updateUIViewController(_ uiViewController: MyViewController, context: UIViewControllerRepresentableContext<MyView>) {
}
}
struct SwiftUIView: View {
@State var isShowingMyVC = false
var body: some View {
Button(action: {
// on tap, go to MyViewController
self.isShowingMyVC = true
}) {
Text("Go to UIViewController")
}
.sheet(isPresented: $isShowingMyVC) {
MyView()
}
}
}
2. 使用按钮操作处理程序。
如果您不希望SwiftUIView
知道它应该与之交互的任何 UIViewController,请让SwiftUIView
有一个由按钮调用的操作处理程序。 然后,在 UIKit 代码中的某处使用它,以显示任何 UIViewController。
struct SwiftUIView: View {
@State var isShowingMyVC = false
var tapHandler: (() -> Void)? = nil
var body: some View {
Button(action: {
// on tap, go to MyViewController
self.tapHandler?()
}) {
Text("Go to UIViewController")
}
.sheet(isPresented: $isShowingMyVC) {
MyView()
}
}
}
let hostingView = UIHostingController(rootView: SwiftUIView() {
self.present(MyViewController(), animated: true, completion: nil)
})
hostingView.view.frame = view.bounds
view.addSubview(hostingView.view)
我不确定这两种方法是否正是您正在寻找的。 只是希望它对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.