我正在学习 SwiftUI,但我遇到了一个问题...如何滚动到顶部 ScrollView
当SegmentedControl
值变了?
这是主 View 显示数据的代码:
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
.
我不得不填写一堆缺失的部分(请在 future 包括所有相关代码),但这是我所拥有的:
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
将被重新创建,这会将其滚动条留在顶部。要测试它,请点击“葡萄酒”,向下滚动一点,然后点击其他任何一个。关于ios - 如何在 SwiftUI 中滚动顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666358/