5

(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

1 Answer 1

6

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

4 Comments

Your answer has helped me a lot. However, is it possible for me to use multiple Text()s in the ForEach loop? When I try it, I get an error saying "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols".
@ElectroMonkey, what do you mean by "multiple Text"? ForEach already creates multiple Text, one per data in integrating array, so once you add new string into array, new Text will be created by ForEach.
Place the Texts into a container like a Stack, and then return the container as the cell's View.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.