GaF
GaF

Reputation: 111

Set the initially visible item LazyGrid (swiftUI)

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

Upvotes: 3

Views: 862

Answers (1)

Asperi
Asperi

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

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

Upvotes: 4

Related Questions