如何从任何类或结构中以模态方式显示SwiftUI视图? 我使用UIKit中的UIHostingController。 有没有更好的方法仅使用SwiftUI来完成这项工作?
ContentView具有呈现SwiftUI视图的按钮
struct ContentView: View {
var body: some View {
Button {
// Present the view
presentView(controller: UIHostingController(rootView: view))
} label: {
Text("Present view")
}
}
var view: some View {
Button {
// Dismiss the view
dismissView()
} label: {
Rectangle()
.overlay(
Text("Dismiss view")
)
}
}
}
用于呈现SwiftUI视图的函数
extension ContentView {
// Returns the top view controller
func topViewController() -> UIViewController? {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if var topController = keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController { topController = presentedViewController }
return topController
} else { return nil }
}
// Presents the SwiftUI view in a UIHostingController
func presentView(controller: UIViewController) {
controller.view.backgroundColor = .none
controller.modalPresentationStyle = .overCurrentContext
topViewController()?.present(controller, animated: false, completion: nil)
}
// Removes the UIHostingViewController from root view
func dismissView() {
topViewController()?.dismiss(animated: false, completion: nil)
}
}