2

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()

        }

    }
}

enter image description here

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, that is what I wanted, I have question maybe I should make a new question topic, but at first I want to be sure if this is possible, could I do same thing that I am doing with CustomContentView() in form of a function?
Not sure what exactly you mean by that. The principle would be the same. But perhaps it's better to start a new question.
@NewDev where did you learn this? Can you give me a reference so I can study it myself?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.