'List unexpected behavior - How to redraw//recreate each RowView?
I have realized that some caching mechanism is present if the List's row is a View.
Let's start with a simple list:
struct ContentView: View {
@State var model = [String]()
var body: some View {
VStack {
Button("Add") {
model.append(UUID().uuidString)
}
List {
ForEach(0 ..< model.count, id:\.self) { idx in
let item = model[idx]
Print("\(idx)")
makeRow(item: item)
}
}
}
}
func makeRow(item: String) -> some View {
HStack {
Print("Row \(item)")
Text("\(item)")
}
}
}
extension View {
func Print(_ vars: Any...) -> some View {
for v in vars { print(v) }
return EmptyView()
}
}
Adding a new single row, this appears on the console:
4
Row 44899379-B7FA-4667-ADB9-86A59EA69EF0
0
Row A219638D-9C6E-42C8-9055-C5569B20D9B8
1
Row B6187186-408F-46B2-A121-840C399CB12F
2
Row 856F873F-8639-4CA4-A832-19EF92BFA7A4
3
Row 0C080275-12D9-451C-8C7A-C8B97C4DE658
Then each row is recreated.
Let's replace each row with a View:
func makeRow(item: String) -> some View {
RowView(item: item)
}
struct RowView: View {
var item: String
var body: some View {
HStack {
Print("Row \(item)")
Text("\(item)")
}
}
}
Now the console shows:
4
Row E55A0F48-5848-4CFE-8612-AB8CC799F532
0
1
2
3
Only the RowView for the just added row is created.
Apparently all the other RowViews all cached. I think this is good in most cases.
I'm working on a complex application and, in some use cases, I need to redraw all the rows.
How can I force to recreate each RowView?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
