有谁知道是否有一个系统可以滚动到 SwiftUI 表中的一行? 我知道我可以使用 List/ScrollView/ScrollViewReader 组合,但理想情况下我正在寻找与
Table
配合使用的东西。
我确实尝试在表格周围使用 ScrollViewReader,但这没有任何作用
https://developer.apple.com/documentation/SwiftUI/Table
我理想地在桌子上寻找一种方法,或者类似的东西
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)
}
}
}
您可以通过提供一组选定的 ID 或单个选定的 ID,使用 ScrollViewReader 滚动到表中的列。
@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)
}
}
}
}
}
我制作了一个示例,可以使用顶部按钮或每当点击一行时随机滚动。输出: