Issue #761
Explicitly specify id
ScrollView {
ScrollViewReader { proxy in
LazyVStack(spacing: 10) {
ForEach(items) { item in
Cell(item: item)
.id(item.id)
}
}
.padding()
.onReceiveKeyboard(onNext: {
onNext()
if let item = selectedItem {
proxy.scrollTo(item.id, anchor: .center)
}
}, onPrevious: {
onPrevious()
if let item = selectedItem {
proxy.scrollTo(item.id, anchor: .center)
}
})
}
}
I usually extract ScrollViewReader
into a helper function that use onChange
to react to state changes
func scrollViewReader<Content: View>(@ViewBuilder content: @escaping () -> Content) -> some View {
ScrollViewReader { proxy in
content()
.onChange(of: itemsHolder.focusItem) { item in
guard let item = item else { return }
withAnimation {
proxy.scrollTo(item.id, anchor: .center)
}
}
}
}