iOS16 UIHostingConfiguration默认边距问题及自定义扩展报错求助
解决UIHostingConfiguration自定义无默认边距扩展的报错问题
你遇到的报错是因为UIHostingConfiguration是带有两个泛型参数的结构体:UIHostingConfiguration<Background, Content>,默认Background类型为EmptyView。原扩展没有明确约束泛型参数,导致编译器无法正确匹配初始化器的类型,从而抛出看似矛盾的类型转换错误。
可行解决方案
以下两种写法都可以解决问题:
方案一:约束Background为默认的EmptyView
extension UIHostingConfiguration where Background == EmptyView { static func noMargin<Content: View>(@ViewBuilder content: () -> Content) -> Self { Self(content: content) .margins(.all, 0) } }
方案二:明确指定返回的泛型类型
extension UIHostingConfiguration { static func noMargin<Content: View>(@ViewBuilder content: () -> Content) -> UIHostingConfiguration<EmptyView, Content> { UIHostingConfiguration<EmptyView, Content>(content: content) .margins(.all, 0) } }
使用方式
调用时和原生写法一致:
let config = UIHostingConfiguration.noMargin { Text("无默认边距的内容") }
内容的提问来源于stack exchange,提问作者red
相关产品推荐
相关产品推荐

