Reputation: 111
I'm trying to set the initially visible item LazyGrid (swiftUI)
The idea is instead of the initial value be the default (0)
the initial value became the value I chose, for instance 4
with the possibility of move the grid to 0 and to 9.
I have simple grid
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: [GridItem(.flexible(minimum: 200, maximum: 200))]) {
ForEach(0 ..< 10){ val in
ZStack{
Rectangle()
.foregroundColor(.gray)
.frame(width: 200, height: 200)
Text("\(val)")
.fontWeight(.bold)
.font(.title)
.foregroundColor(.white)
}
}
}
}
}
}
Upvotes: 3
Views: 862
Reputation: 258285
SwfitUI 2.0
There is ScrollViewReader
for this purpose. We give id
for views and by scroll view proxy specify which view should be visible.
Here is a demo. Tested with Xcode 12 / iOS 14
struct DemoView: View {
let initiail: Int = 4
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader { sp in
LazyHGrid(rows: [GridItem(.flexible(minimum: 200, maximum: 200))]) {
ForEach(0 ..< 10, id: \.self){ val in
ZStack{
Rectangle()
.foregroundColor(.gray)
.frame(width: 200, height: 200)
Text("\(val)")
.fontWeight(.bold)
.font(.title)
.foregroundColor(.white)
}.id(val)
}
}.onAppear { sp.scrollTo(initiail) }
}
}
}
}
Upvotes: 4