如何滚动到swiftui

问题描述 投票:0回答:8

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 } } } } } }

swift swiftui
8个回答
23
投票

我认为目前最好的方法是使用视图的ID函数

teclare具有唯一ID

的状态var

13
投票

    然后将ID函数添加到scrollview
  1. ScrollView(.horizontal, showsIndicators: true) { // ... }.id(self.scrollViewID)

    
    
  2. 当您更改该ID时 - 例如在按钮事件中 - 滚动视图是从头开始重建的 - 就像滚动到top
  3. 刚刚出版了
    ScrollViewProxy

代理值允许在视图层次结构中以编程方式滚动的滚动视图。 -

https://developer.apple.com/documentation/swiftui/scrollviewproxy

5
投票

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代码:


4
投票

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 } }
    

1
投票
I找到了有关如何在Apple开发人员页面上滚动到我视图的完整信息:
Https://developer.apple.com/documentation/swiftui/scrollviewReader

0
投票
在我需要滚动列表中的项目时,我需要滚动到视图的顶部。我遵循了苹果的榜样,并用

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

0
投票

课程从iOS 14.0及以后您应该使用

ScrollViewProxy

,绝对是出于此原因而开发的。

但是,如果您检查何时问问题,您将定义答案是针对
IOS13.0,SwiftUi1.0

,在此时间点,您必须以某种方式重新发明自行车:
使用this

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.