![](/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.