在 SwiftUI 中动态添加元素到 VStack

ary*_*anm 5 uiscrollview swift swiftui vstack

(Swift 5,SwiftUI)如果我有以下 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))
    }
}
}
Run Code Online (Sandbox Code Playgroud)

如何通过函数动态地将 Text() 添加到 VStack 并相应地更新 ScrollView 高度?

该函数(通过按下按钮调用):

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.
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种简单的方法来将 Text() 元素添加到我的 VStack 中。我在谷歌上广泛搜索了这个问题,但没有发现任何与这个小问题类似的东西。任何帮助,将不胜感激。

Asp*_*eri 6

这是可能解决方案的演示。使用 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")
    }
}
Run Code Online (Sandbox Code Playgroud)