Does anyone know if there's a system to scroll to a row in a SwiftUI Table?
I know I can use a List/ScrollView/ScrollViewReader combination, but I'm ideally looking for something that works with Table.
I did try using a ScrollViewReader around a Table, but that did nothing
https://developer.apple.com/documentation/SwiftUI/Table
I'm ideally looking for a method on the Table, or something like a TableReader
struct Person: Identifiable {
let givenName: String
let familyName: String
let emailAddress: String
let id = UUID()
}
private var people = [
Person(givenName: "Juan", familyName: "Chavez", emailAddress: "[email protected]"),
Person(givenName: "Mei", familyName: "Chen", emailAddress: "[email protected]"),
Person(givenName: "Tom", familyName: "Clark", emailAddress: "[email protected]"),
Person(givenName: "Gita", familyName: "Kumar", emailAddress: "[email protected]")
.... 100 more....
]
var body: some View {
ScrollViewReader { proxy
Table(people) {
TableColumn("Given Name", value: \.givenName)
TableColumn("Family Name", value: \.familyName)
TableColumn("E-Mail Address", value: \.emailAddress)
}
.onChange(of: selection) { newValue in
proxy.scrollTo(newValue, anchor: .center)
}
}
}
You can scroll to a row in a Table with ScrollViewReader, by providing a set of selected IDs or a single selected ID.
@State private var selectedPerson: Person.ID?
var body: some View {
ScrollViewReader { proxy in
VStack {
Button {
selectedPerson = people.randomElement()?.id
} label: {
Text("Scroll")
}
Table(people, selection: $selectedPerson) {
TableColumn("Given Name", value: \.givenName)
TableColumn("Family Name", value: \.familyName)
TableColumn("E-Mail Address", value: \.emailAddress)
}
.onChange(of: selectedPerson) { newValue in
withAnimation {
proxy.scrollTo(newValue, anchor: .center)
}
}
}
}
}
I've made an example to scroll randomly or whenever you tap on a row. Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With