SwiftUI-如何从SwiftUI访问UIHostingController
我有SwiftUI页面,它是从UIKit视图导航的。我想为这个页面设置一个标题,我正在做的是SwiftUI-如何从SwiftUI访问UIHostingController,swiftui,uihostingcontroller,Swiftui,Uihostingcontroller,我有SwiftUI页面,它是从UIKit视图导航的。我想为这个页面设置一个标题,我正在做的是 // code of UIKit view let controller = UIHostingController(rootView: SwiftUIView()) controller.title = "title" MyNavigationManager.present(controller) 有没有办法访问SwiftUI中的主机控制器 然后我就可以像这样写代码了 self
// code of UIKit view
let controller = UIHostingController(rootView: SwiftUIView())
controller.title = "title"
MyNavigationManager.present(controller)
有没有办法访问SwiftUI中的主机控制器
然后我就可以像这样写代码了
self.hostingController?.title=“title”
这里是一个可能方法的演示-使用外部配置包装类来保存到控制器的弱链接,并将其注入SwiftUI视图(作为替代,也可以使其与其他全局属性和逻辑相结合)
使用Xcode 12.5/iOS 14.5进行测试
class Configuration {
weak var hostingController: UIViewController? // << wraps reference
}
struct SwiftUIView: View {
let config: Configuration // << reference here
var body: some View {
Button("Demo") {
self.config.hostingController?.title = "New Title"
}
}
}
let configuration = ExtConfiguration()
let controller = UIHostingController(rootView: SwiftUIView(config: configuration))
// injects here, because `configuration` is a reference !!
configuration.hostingController = controller
controller.title = "title"
MyNavigationManager.present(controller)
类配置{
弱var hostingController:UIViewController?//最后,我选择了一种简单的方法,在托管控制器中,将self传递到SwiftUI rootView.hostingController=self