SwiftUI,将视图作为参数传递给@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
            }
        }
    }
}

任何方法都可以实现吗?

解决方法

可能的解决方案是使用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
        ))
    }
}