swiftPunk
swiftPunk

Reputation: 1

How I can feed a Custom-View with a View in SwiftUI?

I got a CustomVStackView() which I am using it inside my ContentView(), My Goal is to be able feed CustomVStackView() with an other View from ContentView().

Here the Code, it has issue with it!

    struct ContentView: View {
 
    
    var body: some View {

        CustomVStackView(inPutView: Text("Hello").font(Font.largeTitle) )
        
    }
}


struct CustomVStackView: View {
    

    
    var inPutView: View = EmptyView()
    
    var body: some View {
        

        VStack
        {
            inPutView
 
        }.padding().background(Color.purple)
        
        
    }
}

PS: I know about AnyView() but I am interested to feed my inPutView with a decent normal View() like Text() or Circle() . . .

Upvotes: 0

Views: 196

Answers (1)

New Dev
New Dev

Reputation: 49590

You'd have to use generics to be able to pass any arbitrary view. In this case, CustomVStackView will have a generic type Content that conforms to View.

If you also use @ViewBuilder for the parameter, then the user of CustomVStackView would be able to use the same syntax for the inner view that is used for the normal VStack (and throughout SwiftUI):

struct CustomVStackView<Content: View>: View {
    
    private var inputView: () -> Content

    init(@ViewBuilder inputView: @escaping () -> Content) {
        self.inputView = inputView
    }
    
    var body: some View {
        VStack
        {
            inputView()
        }
        .padding().background(Color.purple)
    }
}

Usage is:

CustomVStackView() {
    Text("Hello").font(Font.largeTitle)
    Text("World")
}

Upvotes: 1

Related Questions