swiftPunk
swiftPunk

Reputation: 1

How can I define default empty input content for a View in SwiftUI?

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

Upvotes: 2

Views: 646

Answers (1)

New Dev
New Dev

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

Related Questions