SwiftUI,将视图作为参数传递给@Viewbuilder

时间:2020-10-14 11:02:12

标签: ios struct swiftui swift-protocols viewbuilder

出于好奇,我将View类型作为参数传递给@ViewBuilder。在@ViewBuilder中将Model / Primitive类型作为参数传递是完全有效的。

如下面的代码所示。

struct TestView<Content: View>: View {
    
    let content: (String) -> Content
    
    init(@ViewBuilder content: @escaping (String) -> Content) {
        self.content = content
    }
    
    var body: some View {
        content("Some text")
    }
}

struct ContentTestView: View {
    
    var body: some View {
        TestView {
            Text("\($0)")
        }
    }
}

代替String

let content: (String) -> Content

如果我尝试传递SwiftUI View类型,则编译器对此不满意。

let content: (View) -> Content

即使@ViewBuilder的参数接受Searchable之类的自定义协议类型,但不接受View协议。

编译器告诉我这个Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements

我的整个想法是可以允许content容纳Section/List/Text

编辑:我期望下面的代码。

struct TestView<Content: View>: View {

    let content: (View) -> Content

    init(@ViewBuilder content: @escaping (View) -> Content) {
        self.content = content
    }

    var body: some View {
        content(
            List {
                ForEach(0..<10) { i in
                    Text(\(i))
                }
            }
        )
    }
}

struct ContentTestView: View {

    var body: some View {
        TestView { viewbody -> _ in
            
            Section(header: Text("Header goes here")) {
                viewbody
            }
        }
    }
}

任何方法都可以实现吗?

1 个答案:

答案 0 :(得分:0)

可能的解决方案是使用AnyView,例如

struct TestView<Content: View>: View {
    
    let content: (AnyView) -> Content
    
    init(@ViewBuilder content: @escaping (AnyView) -> Content) {
        self.content = content
    }
    
    var body: some View {
        content(AnyView(
            Text("Demo")   // << put here any view hierarchy
        ))
    }
}