大佬教程收集整理的这篇文章主要介绍了SwiftUI ScrollView 根据下拉列表的更改以编程方式滚动到顶部,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码:
var body: some VIEw {
vstack {
ScrollVIEw {
vstack {
ForEach(1...7,ID: \.self) { num in
Text("\(num)")
.Font(.title3)
.padding([.top,.bottom],5)
.onTapGesture {
self.getGames()
}
}
}
}
ScrollVIEw() {
GameCell(games: $games,picks: self.$playerPicks)
}
.onAppear(perform: getGames)
}
}
它根据 num 的值获取所有游戏和所有游戏;因为它应该基于 .onAppear(perform: getGames)
当 num 被选中时,它会用 GameCell 刷新主 ScrollVeiw 但如果主 ScrollVIEw(带有 GameCells)被滚动到任何位置,当数据刷新时它会停留在那个位置......有没有办法让它滚动到主 ScrollVIEw 的顶部(带有 GameCells)?
更新
我更新了上面的代码,有两个滚动视图,我想让第二个滚动视图在每次在第一个滚动视图中选择新值时让 GameCells 滚动到顶部。
您可以使用 ScrollViewReader
(docs & HWS articlE)。
对于您的用例,我们需要将 ScrollViewProxy
保存在 @State
变量中,以便可以在闭包之外访问它。像这样使用它:
struct ContentView: View {
@State private var reader: ScrollViewProxy?
var body: some View {
VStack {
ScrollView {
VStack {
ForEach(1 ... 7,id: \.self) { num in
Text("\(num)")
.font(.title3)
.padding([.top,.bottom],5)
.onTapGesture {
self.getGames()
print("Tap:",num)
// Scroll to tag 'GameCell-top'
reader?.scrollTo("GameCell-top",anchor: .top)
}
}
}
}
ScrollView {
ScrollViewReader { reader in
LinearGradient(
gradient: Gradient(colors: [.red,.blue]),startPoint: .top,endPoint: .bottom
)
.frame(height: 1000)
.id("GameCell-top") // <- ID so reader works
.tag("GameCell-top") // <- Tag view for reader
.onAppear {
self.reader = reader // <- Set current reader proxy
}
// You can uncomment this view and do a similar thing to the VStack above
// GameCell(games: $games,picks: self.$playerPicks)
}
}
.onAppear(perform: getGames)
}
}
}
结果(我滚动底部滚动视图,然后点击顶部从 1 到 7 的任意数字):
以上是大佬教程为你收集整理的SwiftUI ScrollView 根据下拉列表的更改以编程方式滚动到顶部全部内容,希望文章能够帮你解决SwiftUI ScrollView 根据下拉列表的更改以编程方式滚动到顶部所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。