My curiosity takes me to pass a View
type as parameter to @ViewBuilder
. Passing a Model/Primitive type as param in @ViewBuilder
is perfectly valid.
As shown below code.
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)")
}
}
}
In place of String
in
let content: (String) -> Content
If I try to pass a SwiftUI View
type, then Compiler is not happy with it.
let content: (View) -> Content
Even though params for @ViewBuilder
accepts custom Protocol type like Searchable
but not View
protocol.
compiler tell me this Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
My whole idea is that content
can be allowed to hold Section/List/Text
in it.
Edit: I expected code like below.
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
}
}
}
}
Any way can I achieve this ?
TestView { ??? in
, as ??? will be an opaque unknown, for you, view? – Pilarpilaster