在 SwiftUI 中动态添加元素到 VStack
Dynamically add elements to VStack in SwiftUI
(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 的简单方法。我在 Google 上广泛搜索了这个问题,但没有发现与这个微不足道的问题类似的问题。任何帮助将不胜感激。
这是一个可能的解决方案演示。使用 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 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 的简单方法。我在 Google 上广泛搜索了这个问题,但没有发现与这个微不足道的问题类似的问题。任何帮助将不胜感激。
这是一个可能的解决方案演示。使用 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")
}
}