[英]SwiftUI how to update List dynamic
I'm using SwiftUI just started.我正在使用刚刚开始的 SwiftUI。 I often confused how difference between Declarative programming and Imperative programming.
我经常混淆声明式编程和命令式编程之间的区别。
Console log show error:控制台日志显示错误:
ForEach<Range, Int, Text> count (2).= its initial count (1).
ForEach<Range, Int, Text> 计数 (2).= 其初始计数 (1)。
ForEach(_:content:)
should only be used for constant data.ForEach(_:content:)
应该只用于常量数据。 Instead conform data toIdentifiable
or useForEach(_:id:content:)
and provide an explicitid
!而是使数据符合
Identifiable
或使用ForEach(_:id:content:)
并提供明确的id
!
Why?How to update list dynamically?How dose SwiftUI handle data source?为什么?如何动态更新列表?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:)
differs from ForEach(_:content:)
by the id
parameter. ForEach(_:id:content:)
与ForEach(_:content:)
:) 的区别在于id
参数。
If you use a static ForEach
the loop is generated once and not refreshed when you modify the n
.如果您使用 static
ForEach
循环生成一次并且在您修改n
时不会刷新。
Try this:尝试这个:
struct AView: View {
let n: Int
var body: some View {
List {
ForEach(0 ..< n, id:\.self) { i in // <- add `id` parameter
Text(String(i))
}
}
}
}
You can take a look at Why does.self work for ForEach?你可以看看Why does.self for ForEach? for a more detailed explanation.
以获得更详细的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.