swiftPunk
swiftPunk

Reputation: 1

How can I use a VStack as input for a func in SwiftUI?

I just made a func that take Text as input and add that Text to an array of AnyView, I want do same thing with a VStack, here my example code for Text which is working, just want same functionally for VStack, thanks for reading and your time.

    struct ContentView: View {
    
    init() {
        appendThisText(text: Text("Hello, world1!") )
        appendThisText(text: Text("Hello, world2!") )
        appendThisText(text: Text("Hello, world3!") )
    }
    
    var body: some View {

        ForEach(myAnyTexts.indices, id:\.self) { index in
            
            myAnyTexts[index]
            
        }
        
    }
}

var myAnyTexts: [AnyView] = [AnyView]()

func appendThisText(text: Text) {
    
    myAnyTexts.append(AnyView(text))
    
}

    var myAnyVStacks: [AnyView] = [AnyView]()


func appendThisVStack(vStack: VStack<Content: View>) {       // Here: the problem!
    
    myAnyVStacks.append(AnyView(vStack))
    
}

updated for you to quality code:

var myAnyContents: [AnyView] = [AnyView]()

func appendThisContent<Content: View>(content: Content) {
    
    myAnyContents.append(AnyView(content))
    
}

Upvotes: 1

Views: 289

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 18994

Add view constraint

func appendThisVStack<Content: View>(vStack: Content) { //<-- Here
    
    myAnyVStacks.append(AnyView(vStack))
    
}

Upvotes: 1

Related Questions