应用`listRowInsets`时SwiftUI列表未更新 [英] SwiftUI List not getting updated when `listRowInsets` are applied
问题描述
点击更新List
中的数据
当 .listRowInsets
应用于列表行时,列表在状态改变时停止获取更新.
When .listRowInsets
are applied to the list rows, the list stops getting updates when the state changes.
struct ContentView: View {
private var array = ["a", "b", "c"]
@State private var selectedIndex = 0
var body: some View {
makeBody()
}
private func makeRow(_ t: String, index: Int) -> some View {
return HStack {
Text(t)
Spacer()
if selectedIndex == index {
Image(systemName: "checkmark.circle")
}
}
.contentShape(Rectangle())
.onTapGesture {
print("selected \(index)")
self.selectedIndex = index
}
}
private func makeBody() -> some View {
return List {
ForEach(0..<array.count) { i in
self.makeRow(self.array[i], index: i)
// comment and uncomment this line
// .listRowInsets(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20))
}
}
}
}
问题
这是一个错误吗?还是我遗漏了什么?
Question
Is this a bug? Or am I missing something?
推荐答案
如果您的数据可以更改,您需要一个动态的 ForEach
循环(带有显式的 id
参数):
If your data can be changed, you need a dynamic ForEach
loop (with an explicit id
parameter):
ForEach(0..<array.count, id:\.self) { i in // <- add `id:\.self`
self.makeRow(self.array[i], index: i)
.listRowInsets(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20))
}
虽然没有很好的记录.在某些情况下,当您尝试修改 ForEach 循环中使用的数组时,Xcode 会警告您:
It's not well documented though. In some cases Xcode warns you when you try to modify your array used in a ForEach loop:
ForEach(_:content:)
应该只用于常量 数据.而是使数据符合 Identifiable
或使用 ForEach(_:id:content:)
并提供一个明确的id
!
ForEach(_:content:)
should only be used for constant data. Instead conform data toIdentifiable
or useForEach(_:id:content:)
and provide an explicitid
!
这篇关于应用`listRowInsets`时SwiftUI列表未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!