Set the initially visible item LazyGrid (swiftUI)

Viewed 474

I'm trying to set the initially visible item LazyGrid (swiftUI)

The idea is instead of the initial value be the default (0)

enter image description here

the initial value became the value I chose, for instance 4

enter image description here

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)
                    }
                }
            }
        }
    }
}
1 Answers

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

demo

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