struct Example: View {
private static let topId = "topIdHere"
/*
Use only for toggling, binding for external access or @State for internal access
*/
@Binding var shouldScrollToTop: Bool = false
var body: some View {
ScrollViewReader { reader in // read scroll position and scroll to
ScrollView {
VStack {
TopView() // << first view on top
.id(Self.topId) // << assigned id (use for scroll)
}
.onChange(shouldScrollToTop) { _ in
withAnimation { // add animation for scroll to top
reader.scrollTo(Self.topId, anchor: .top) // scroll
}
}
}
}
}
}
我认为目前最好的方法是使用视图的ID函数
teclare具有唯一ID
的状态var
ScrollView(.horizontal, showsIndicators: true) {
// ...
}.id(self.scrollViewID)
刚刚出版了
ScrollViewProxy
代理值允许在视图层次结构中以编程方式滚动的滚动视图。 -
https://developer.apple.com/documentation/swiftui/scrollviewproxy
XCode 12.0 beta(12A6159)
///滚动到顶部的方式:
struct MyView: View { @State var scrollToTopVar = false var body: some View { VStack { //will scroll to top on button press Button("Scroll to top") { scrollToTopVar.toggle() } ScrollViewReader { reader in ScrollView { ScrollerToTop(reader: reader, scrollOnChange: $scrollToTopVar) VStack { //Some Views } } } } } }
SCrollerTopop代码:
ScrollViewReader { proxy in
ScrollView {
content
.id("content")
}
.onChange(of: store.step) { // some state change triggers scroll
proxy.scrollTo("content", anchor: .top)
}
}
有一个解决方法,可以通过在显示新内容之前隐藏所有内容来完成scrolltotop()效果。
@State var hideEverything = false
var body: some View {
ScrollView {
if hideEverything {
EmptyView()
} else {
// your content view
}
}
}
func ScrollToTop() {
self.hideEverything = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01)
{
self.data = ... // update data source
self.hideEverything = false
}
}
Https://developer.apple.com/documentation/swiftui/scrollviewReader
ScrollViewReader
包裹了滚动视图。
@Namespace var topID
var body: some View {
ScrollViewReader { proxy in
VStack {
Section {
//
//
}
.id(topID)
ForEach(Array(...)) { index, xxx in
Section {
//
//
}
.onTapGesture {
withAnimation {
proxy.scrollTo(topID)
}
}
} //ForEach
} //VStack
} //ScrollViewReader
} //body
课程从iOS 14.0及以后您应该使用
ScrollViewProxy
,绝对是出于此原因而开发的。
但是,如果您检查何时问问题,您将定义答案是针对IOS13.0,SwiftUi1.0,在此时间点,您必须以某种方式重新发明自行车:使用this