Dynamically add elements to VStack in SwiftUI

Viewed 3993

(Swift 5, SwiftUI) If I have the following code for a VStack:

struct ContentView: View {

var body: some View {

    ScrollView {
        VStack(alignment: .leading) {

                //Inside of VStack

        }.padding()
        .padding(.bottom, keyboard.currentHeight)
        .edgesIgnoringSafeArea(.bottom)
        .animation(.easeOut(duration: 0.16))
    }
}
}

How can I dynamically add Text()s to the VStack through a function and update the ScrollView height accordingly?

The function (is called by a button press):

func add() -> Void {
    //Adds a Text() element to the VStack. The content of the Text() is received from an API 
    //call, so it can't be hardcoded.
}

I'm looking for a simple way to add Text() elements to my VStack. I've extensively searched for the problem on Google but found nothing similar to this trivial problem. Any help would be appreciated.

1 Answers

Here is a demo of possible solution. Tested with Xcode 11.4

struct ContentView: View {
    @State private var texts: [String] = [] // storage for results
    var body: some View {

        ScrollView {
            VStack(alignment: .leading) {
                ForEach(texts, id: \.self) { text in // show received results
                    Text(text)
                }
            }.frame(maxWidth: .infinity)  // << important !!
            .padding()
                .padding(.bottom, keyboard.currentHeight)
                .edgesIgnoringSafeArea(.bottom)
                .animation(.easeOut(duration: 0.16))
        }
    }

    func add() -> Void {
        // store result string (must be on main queue)
        self.texts.append("result")
    }
}
Related