问题描述
我有 SwiftUI 页面,它是从 UIKit 视图导航的。我想给这个页面设置一个标题,我正在做的是
// code of UIKit view
let controller = UIHostingController(rootView: SwiftUIView())
controller.title = "title"
MyNavigationManager.present(controller)
有没有办法在 SwiftUI 中访问托管控制器?
然后我可以写代码
self.hostingController?.title = "title"
解决方法
这是一个可能的方法的演示 - 使用外部配置包装类来保持控制器的弱链接并将其注入 SwiftUI 视图(作为替代,也可以使其 ObservableObject
与其他全局属性结合和逻辑)。
使用 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)