You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:36:04