Ber*_*lue 4 scrollview ios swift swiftui
我有一个水平滚动的 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)")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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)")
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2847 次 |
最近记录: |