SwiftUI如何滚动到指定的位置
在 SwiftUI 中,实现 ScrollView 滚动到底部的功能,需要一些额外的步骤,因为 SwiftUI 的 ScrollView 默认并不提供直接的滚动控制。可以通过使用 ScrollViewReader 来实现这个功能。ScrollViewReader 提供了一个环境,其中可以使用其 proxy 对象来操作滚动视图的位置。
ScrollViewReader { scrollViewProxy in
ScrollView {
VStack {
Button(action: {
...
}, label: {
...
})
....
Button(action: {
...
}, label: {
...
})
}
}
}
如上面代码所示,如果需要滚动到底部的Button,只需要给底部Button加个id属性,如:
Button(action: {
...
}, label: {
...
})
.id("lastButton")
然后就可以使用
scrollViewProxy.scrollTo("lastButton", anchor: .bottom)
将ScrollView滚动到底部了,也可以给他加个动画:
withAnimation {
scrollViewProxy.scrollTo("lastButton", anchor: .bottom)
}