应用 `listRowInsets` 时,SwiftUI 列表未更新
SwiftUI List not getting updated when `listRowInsets` are applied
目标
点击 List
更新数据
问题
当 .listRowInsets
应用于列表行时,列表会在状态更改时停止更新。
代码
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))
}
}
}
}
问题
这是一个错误吗?还是我遗漏了什么?
如果您的数据可以更改,则需要一个动态 ForEach
循环(带有显式 id
参数):
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 会警告您:
ForEach(_:content:)
should only be used for constant data.
Instead conform data to Identifiable
or use ForEach(_:id:content:)
and provide an explicit id
!
目标
点击 List
更新数据
问题
当 .listRowInsets
应用于列表行时,列表会在状态更改时停止更新。
代码
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))
}
}
}
}
问题
这是一个错误吗?还是我遗漏了什么?
如果您的数据可以更改,则需要一个动态 ForEach
循环(带有显式 id
参数):
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 会警告您:
ForEach(_:content:)
should only be used for constant data. Instead conform data toIdentifiable
or useForEach(_:id:content:)
and provide an explicitid
!