I'm trying to add an item to the bottom of a List and then scroll that added item into view. I've made the following code that can be entered directly into a new iOS project in Xcode (14 beta 3) to replicate the problem (which is an exception after adding an item 3 times). I have tried many variations of the ID used in the "id" field of ForEach, the ".id" modifier on the text, as well as in the "scrollTo" method. Nothing works for me -- I get the same behavior no matter what I use: The first item scrolls into view as desired; the second item does not scroll; and the third item crashes.
I've left in the code a ".onDelete" modifier because it literally takes 3 items added before the crash will occur. So, you could add 2 items, delete one of those, and then it would take two more adds (still for a total of 3 items in the List) to see the crash. I'm baffled. It doesn't seem to matter how many items I start the list with (4 in this case)... it is always the third addition that crashes.
Any thoughts? Thanks for any help.
struct ContentView: View {
@State var data = [1, 2, 3, 4]
@State var count = 4
var body: some View {
VStack {
ScrollViewReader { proxy in
List {
ForEach(data, id: \.self) { datum in
Text("\(datum)")
.id(datum)
}
.onDelete {
data.remove(atOffsets: $0)
}
}
.onChange(of: data) { _ in
proxy.scrollTo(data.last)
}
}
Button {
count += 1
data.append(count)
} label: {
Text("Add")
}
}
}
}