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

4

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

在UIKit中,我会创建一个水平滚动的UICollectionView并设置collectionView.contentOffset来设置初始滚动位置,但是我不知道在SwiftUI中该怎么做。

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

6

您可以使用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)
            }
        }
    }
}

嗨!谢谢你提供这个很棒的答案。有一个问题,它能用于自定义结构体/类吗? - Alexander Khitev
1
@AlexanderKhitev 当然,但你需要知道SwiftUI的视图是结构体。 - Shehata Gamal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接