在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))
    }
}
}

如何通过函数向VStack动态添加Text()并相应地更新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.
}

我正在寻找一种将Text()元素添加到我的VStack的简单方法。我已经在Google上广泛搜索了该问题,但没有发现与这个琐碎问题类似的问题。任何帮助将不胜感激。

iCMS 回答:在SwiftUI中向VStack动态添加元素

这里是可能解决方案的演示。用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")
    }
}
本文链接:https://www.f2er.com/2256953.html

大家都在问