繁体   English   中英

如何在 SwiftUI 的 LazyHStack 中设置滚动 position

[英]How to set the scroll position in a LazyHStack in SwiftUI

我有一个水平滚动的 LazyHStack。 如何设置初始滚动 position?

In UIKit, I would create a horizontally scrolling UICollectionView and set the collectionView.contentOffset to set the initial scroll position, but I'm not sure how to do this in SwiftUI.

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack {
                ForEach(1...100, id: \.self) { i in             
                    Text("\(i)")
                }
            }
        }
    }   
}

您可以使用ScrollViewReader

手动滚动

struct ContentView: View {
    var body: some View {
        ScrollViewReader { value in
            Button("Go to #15") {
                value.scrollTo(15, anchor: .center)
            }
            ScrollView(.horizontal) {
                LazyHStack(alignment: .top, spacing: 10) {
                    ForEach(1...100, id: \.self) {
                        Text("Column \($0)")
                    }
                }
            }
        }
    }
}

自动滚动

struct ContentView: View {
    var body: some View {
        ScrollViewReader { value in
            ScrollView(.horizontal) {
                LazyHStack(alignment: .top, spacing: 10) {
                    ForEach(1...100, id: \.self) {
                        Text("Column \($0)")
                    }
                }
            }
            .onAppear {
                value.scrollTo(15, anchor: .center)
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM