[英]How can I scrollToTop in SwiftUI
我正在学习 SwiftUI,但我遇到了一个问题...当SegmentedControl
值发生变化时,如何在ScrollView
滚动到顶部?
这是主视图显示数据的代码:
var body: some View {
NavigationView {
SegmentedControl(selection: $selected) {
Text("Food").tag(0)
Text("Drinks").tag(1)
Text("Wines").tag(2)
}
.padding()
ScrollView {
VStack(alignment: .center) {
if selected == 0 {
ForEach (persons) {
AnyCell(person: $0, animal: nil, wine: nil)
}
} else if selected == 1 {
ForEach (animals) {
AnyCell(person: nil, animal: $0, wine: nil)
}
} else {
ForEach (wines) {
AnyCell(person: nil, animal: nil, wine: $0)
}
}
}
}
.navigationBarTitle(Text("Food list"), displayMode: .inline)
}
}
谢谢
在 SwiftUI 中,如果你改变一个变量的值,任何依赖于它的body
属性都将被重新计算。 在您的情况下,只需更改选择即可完全重置ScrollView
。
我不得不填写一堆缺失的部分(请在未来包括所有相关代码),但这是我所拥有的:
import SwiftUI
let people = ["John", "Sarah", "Cathy"]
let animals = ["Cat", "Dog", "Rabbit", "Bird", "Lion", "Snake", "Cat", "Dog", "Rabbit", "Bird", "Lion", "Snake"]
let wines = ["Sauvignon Blanc", "Syrah", "Pinot Noir", "Champagne", "Sauvignon Blanc", "Syrah", "Pinot Noir", "Champagne", "Sauvignon Blanc", "Syrah", "Pinot Noir", "Champagne", "Sauvignon Blanc", "Syrah", "Pinot Noir", "Champagne"]
struct ContentView : View {
@State var selected: Int = 0
var body: some View {
NavigationView {
VStack {
SegmentedControl(selection: $selected) {
Text("Food").tag(0)
Text("Drinks").tag(1)
Text("Wines").tag(2)
}
.padding()
if selected == 0 {
ScrollView {
VStack(alignment: .center) {
ForEach (people.identified(by: \.self)) {
CellView(title: $0)
}
}
}
} else if selected == 1 {
ScrollView {
VStack(alignment: .center) {
ForEach (animals.identified(by: \.self)) {
CellView(title: $0)
}
}
}
} else {
ScrollView {
VStack(alignment: .center) {
ForEach (wines.identified(by: \.self)) {
CellView(title: $0)
}
}
}
}
}.navigationBarTitle(Text("Food list"), displayMode: .inline)
}
}
}
struct CellView : View {
let title: String
var body: some View {
Text(title).font(.largeTitle).frame(height: 100).background(Color.green)
}
}
当您更改selected
,将重新创建ScrollView
,这会将其滚动条留在顶部。 要测试它,请点击“葡萄酒”,向下滚动一点,然后点击其他任何一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.