咨询:如何从UIHostingController获取内嵌SwiftUI视图及属性
解决SwiftUI视图内嵌UIKit时获取属性的问题
在UIKit中我们可以直接存储并转换自定义UIView获取属性,但SwiftUI视图被包裹在UIHostingController中,直接转换UIHostingController.view会失败,因为两者属于不同类型体系。以下是几种可行的解决方式:
方法一:存储UIHostingController而非其View
直接保存UIHostingController实例,通过它的rootView属性直接访问SwiftUI视图的属性:
// 定义存储HostingController的数组 var hostingControllers = [UIHostingController<MySwiftUIContentView>]() var viewsArray = [UIView]() let heights = [50.0, 100.0] for height in heights { let hostingController = UIHostingController(rootView: MySwiftUIContentView(customHeight: height)) hostingControllers.append(hostingController) viewsArray.append(hostingController.view) } // 获取属性时 if let hostingController = hostingControllers[index] { print("This view height is \(hostingController.rootView.customHeight)") }
方法二:通过UIView扩展从响应链获取HostingController
如果必须只存储UIView数组,可以通过UIView的响应链向上查找对应的UIHostingController,进而获取SwiftUI视图:
extension UIView { func getHostedSwiftUIView<T: View>() -> T? { var currentResponder: UIResponder? = self while let responder = currentResponder { if let hostingController = responder as? UIHostingController<T> { return hostingController.rootView } currentResponder = responder.next } return nil } } // 使用示例 if let swiftUIView = viewsArray[index].getHostedSwiftUIView() as? MySwiftUIContentView { print("This view height is \(swiftUIView.customHeight)") }
额外提示
如果需要实时监听SwiftUI视图属性的变化,可以在SwiftUI视图中用@Published包装属性,然后在UIKit侧通过Combine订阅变化,这样能更贴合SwiftUI的响应式特性。
内容的提问来源于stack exchange,提问作者Ricardo Isidro
相关产品推荐
相关产品推荐

