Table not updating correctly

Viewed 203

I'm trying out the new Table to show some sorted data with a single column, but I'm having problems with it not updating when items go out of sight. Swapping it out with a simple List fixes it weirdly enough.

Reproduction:

  1. Ensure that macOS Montery (beta 1 or 2) and Xcode 13 Beta 2 are installed
  2. Create a new blank SwiftUI project targeting macOS, with its deployment target set to 12.0
  3. Paste the following code:
struct ContentView: View {
    @State var data: [TestStruct] = []
    
    var sortedData: [TestStruct] {
        return data.sorted(by: { $0.text < $1.text })
    }
    var body: some View {
        Table(sortedData) { // Swapping this with a List fixes everything
            TableColumn("Text", value: \.text)
        }
        .toolbar {
            Button(action: {
                addItem(longString: false)
            }) {
                Text("Add Short")
            }
            Button(action: {
                addItem(longString: true)
            }) {
                Text("Add Long")
            }
        }
    }
    private func addItem(longString: Bool) {
        withAnimation {
            data.append(TestStruct(text: longString ? "This is long so you can differentiate better" : "Short"))
        }
    }
}
struct TestStruct: Identifiable {
    var text: String
    var id = UUID()
}
  1. Run the app, and press the "Add Long" button. This simply adds an item that has a long string.
  2. Without scrolling, spam click the "Add Short" button. Add enough items so that the long string you added previously goes out of the window, plus a few more items.
  3. Once finished, scroll through the table, and you should see there are duplicate long strings, even though you only added one

What is causing this issue? Swapping the Table with a List fixed the problem entirely, but I would like to keep the Table (so I can add more columns later).

Also, is anybody else able to reproduce this issue? I've been able to reproduce on both versions of macOS Montery (beta 1 and 2), with Xcode 13 Beta 2

1 Answers

I can reproduce this and to me it looks like a bug that is caused by so many rows being identical.

For instance I could completely eliminate this bug by changing addItem to make each text value unique:

let count = data.count + 1
data.append(TestStruct(text: 
     longString ? "This is long so you can differentiate better \(count)" : "Short \(count)"))

Another thing to notice is that if you add sorting to the table then clicking the sort arrow will resolve the issue and the duplicates will disappear. So this looks like an obvious bug but we are still in early beta so it will not stop me from using Table in my macOS project and also this is a bit contrived with so many rows having the exact same value.

Related