【问题标题】:SwiftUI how to update List dynamicSwiftUI如何动态更新List
【发布时间】:2020-10-25 17:43:22
【问题描述】:

我刚开始使用 SwiftUI。我经常混淆声明式编程和命令式编程之间的区别。

控制台日志显示错误:

ForEach 计数 (2) != 其初始计数 (1)。 ForEach(_:content:) 应该只用于 constant 数据。反而 使数据符合Identifiable 或使用ForEach(_:id:content:) 和 提供明确的id!

为什么?如何动态更新列表?SwiftUI如何处理数据源?

struct TestView: View {
    @State var n = 1
    var body: some View {
        VStack {
            Button.init("update") {
                self.n += 1
            }
            AView.init(n: n)
        }
    }
}

struct AView: View {
    let n: Int
    var body: some View {
        List {
            ForEach(0..<n) { i in
                Text.init(String(i))
            }
        }
    }
}

【问题讨论】:

    标签: ios list foreach swiftui


    【解决方案1】:

    ForEach(_:id:content:) 与 ForEach(_:content:) 的区别在于 id 参数。

    如果您使用静态ForEach,则循环会生成一次,并且在您修改n 时不会刷新。

    试试这个:

    struct AView: View {
        let n: Int
    
        var body: some View {
            List {
                ForEach(0 ..< n, id:\.self) { i in // <- add `id` parameter
                    Text(String(i))
                }
            }
        }
    }
    

    您可以查看Why does .self work for ForEach?以获得更详细的说明。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多