簡體   English   中英

SwiftUI如何更新列表動態

[英]SwiftUI how to update List dynamic

我正在使用剛剛開始的 SwiftUI。 我經常混淆聲明式編程和命令式編程之間的區別。

控制台日志顯示錯誤:

ForEach<Range, Int, Text> 計數 (2).= 其初始計數 (1)。 ForEach(_:content:)應該只用於常量數據。 而是使數據符合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))
            }
        }
    }
}

ForEach(_:id:content:)ForEach(_:content:) :) 的區別在於id參數。

如果您使用 static 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 for ForEach? 以獲得更詳細的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM