SwiftUI - 如何从 SwiftUI 访问 UIHostingController

问题描述

我有 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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...