我正在試驗 SwiftUI。我已經有一個基于 UIKit 的應用程式在運行,我想集成一個 SwiftUI 視圖。我通過使用 UIHostingController 實作了顯示這個 SwiftUI 視圖。
在這個 SwiftUI 中,我攔截了一個按鈕動作。在這個行動中,我想:
- 檢查是否有導航控制器(它曾經是 UIKit 上的 self.navigationController)
- 能夠從這個 SwiftUI 視圖呈現或推送(通過 self.navigationController)一個新的 UIKit 視圖控制器。
我找不到任何方法來在 SwiftUI 上實作這三件事中的任何一件
uj5u.com熱心網友回復:
您可以通過多種方式執行此操作:委托、關閉或什至與聯合發布者一起使用。我認為最簡單的入門方法是使用動作閉包。它可能看起來像這樣:
struct SwiftUIView: View {
let action: () -> Void
var body: some View {
Button("press me", action: action)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swiftUIView = SwiftUIView(action: handleButtonPress)
let hostingController = UIHostingController(rootView: swiftUIView)
addChild(hostingController)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(hostingController.view)
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
func handleButtonPress() {
print("TODO: Insert navigation controller logic here")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391863.html
