Search code examples
iosswiftlistswiftuiswiftui-list

Reusability support in List in SwiftUI


I'm currently working on a project that uses SwiftUI. I was trying to use List to display a list of let's say 10 items.

Does List supports reusability just like the UITableview?

I went through multiple posts and all of them says that List supports reusability: Does the List in SwiftUI reuse cells similar to UITableView?

But the memory map of the project says something else. All the Views in the List are created at once and not reused.

enter image description here

Edit

Here is how I created the List:

List {
    Section(header: TableHeader()) {
        ForEach(0..<10) {_ in
            TableRow()
        }
    }
}

TableHeader and TableRow are the custom views created.


Solution

  • List actually provides same technique as UITableView for reusable identifier. Your code make it like a scroll view. The proper way to do is providing items as iterating data.

    struct Item: Identifiable {
        var id = UUID().uuidString
        var name: String
    }
    
    @State private var items = (1...1000).map { Item(name: "Item \($0)") }
    ...
    List(items) {
       Text($0.name)
    }
    

    View hierarchy debugger shows only 17 rows in memory enter image description here