gpt4 book ai didi

swift - 在 SwiftUI 中向 VStack 动态添加元素

转载 作者:行者123 更新时间:2023-12-04 09:48:01 24 4
gpt4 key购买 nike

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

如何通过函数将 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.
}

我正在寻找一种将 Text() 元素添加到我的 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")
}
}

关于swift - 在 SwiftUI 中向 VStack 动态添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com