article

Wednesday, May 26, 2021

SwiftUI Grid Layout Using LazyVGrid

SwiftUI Grid Layout Using LazyVGrid
 
//
//  ContentView.swift
//  DevSwiftUI
//
//  Created by Cairocoders
//

import SwiftUI
 
struct Photo: Identifiable {
    var id = UUID()
    var name: String
}

let listphotoloop = (1...11).map { Photo(name: "\($0)") } //1.jpg to 11.jpg Assets.xcassets

struct ContentView: View {
     
    @State var gridLayout: [GridItem] = [GridItem(.flexible()), GridItem(.flexible())]
     
 
    var body: some View {
         
        NavigationView {
            ScrollView {
                LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) {
 
                    ForEach(listphotoloop.indices) { index in
                        
                        Image(listphotoloop[index].name)
                            .resizable()
                            .scaledToFill()
                            .frame(minWidth: 0, maxWidth: .infinity)
                            .frame(height: 200)
                            .cornerRadius(10)
                            .shadow(color: Color.primary.opacity(0.3), radius: 1)
                        
                    }
                } // End ScrollView
                .padding(.all, 10)
                .animation(.interactiveSpring())
                 
            }// End ScrollView
 
            .navigationTitle("Grid Layout Using LazyVGrid")
             
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        self.gridLayout = Array(repeating: .init(.flexible()), count: self.gridLayout.count % 4 + 1)
                    }) {
                        Image(systemName: "square.grid.2x2")
                            .font(.title)
                            .foregroundColor(.primary)
                    }
                }
            }
             
        } // End Navigation
         
    } // End body
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post