我有一个LazyVStack
我只想更新一个视图而不是在屏幕上重新加载所有其他视图。对于更复杂的单元,这会对性能造成很大影响。我已经包含了示例代码
import SwiftUI
struct ContentView: View {
@State var items = [String]()
var body: some View {
ScrollView {
LazyVStack {
ForEach(self.items, id: \.self) { item in
Button {
if let index = self.items.firstIndex(where: {$0 == item}) {
self.items[index] = "changed \(index)"
}
} label: {
cell(text: item)
}
}
}
}
.onAppear {
for _ in 0...200 {
self.items.append(NSUUID().uuidString)
}
}
}
}
struct cell: View {
let text: String
init(text: String) {
self.text = text
print("init cell", text)
}
var body: some View {
Text(text)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
正如您所看到的,即使仅更改 1 个单元格,也会为每个单元格调用 init。有没有办法避免这种情况?