article

Wednesday, May 26, 2021

SwiftUI Grid Layout Using LazyVGrid

SwiftUI Grid Layout Using LazyVGrid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
//  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