【问题标题】:Dynamically add elements to VStack in SwiftUI在 SwiftUI 中动态添加元素到 VStack
【发布时间】:2020-05-28 11:34:54
【问题描述】:

(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()s动态添加到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 的简单方法。我在谷歌上广泛搜索了这个问题,但没有发现与这个微不足道的问题类似的东西。任何帮助将不胜感激。

【问题讨论】:

标签: swift uiscrollview swiftui vstack


【解决方案1】:

这是一个可能解决方案的演示。使用 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")
    }
}

【讨论】:

  • 您的回答对我帮助很大。但是,我可以在 ForEach 循环中使用多个 Text() 吗?当我尝试它时,我收到一条错误消息“类型'()'不能符合'视图';只有结构/枚举/类类型可以符合协议”。
  • @ElectroMonkey,“多文本”是什么意思? ForEach 已经创建了多个 Text,每个数据在集成数组中创建一个,因此一旦将新字符串添加到数组中,新 Text 将由 ForEach 创建。
  • @Asperi 你能看看这个stackoverflow.com/questions/68325402/…
猜你喜欢
  • 2020-12-07
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多