Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Table scrollTo

Tags:

swiftui

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)
      }
  }
}
like image 581
Chris Avatar asked May 03 '26 18:05

Chris


1 Answers

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:

enter image description here

like image 176
sonle Avatar answered May 05 '26 07:05

sonle