Reputation: 1
I have CustomContentView() which I like give an empty content like {} as default to it, which I do not have to do it in use case, for example I done same thing for Color!
more info: the answer could solve the issue without using ViewBuilder, or even transforming CustomContentView to function, all is ok until we can be able feed content if we wanted!
struct ContentView: View {
var body: some View {
CustomContentView(content: { Text("hello") })
CustomContentView(content: { })
// I like this one: CustomContentView() How can I do this?
}
}
struct CustomContentView<Content: View>: View {
let content: () -> Content
let color: Color
init( @ViewBuilder content: @escaping () -> Content, color: Color = Color.red) {
self.content = content
self.color = color
}
var body: some View {
ZStack {
Rectangle()
.fill(color)
content()
}
}
}
Upvotes: 2
Views: 646
Reputation: 49590
Because CustomContentView
is a generic type with respect to Content
, and you want a default content to be empty, then you need to create an init
overload constrained to Content
being EmptyView
:
init(color: Color = .red) where Content == EmptyView {
self.init(content: { EmptyView() }, color: color)
}
Usage is as you'd expect:
CustomContentView()
// or
CustomContentView(color: .blue)
Upvotes: 5