出于好奇,我将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
}
}
}
}
任何方法都可以实现吗?
答案 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
))
}
}