Grid in SwiftUI

In previous posts we have worked on TableView (List), now you would be curious to know about the CollectionView or Grid in SwiftUI.
So there is no such thing as CollectionView in SwiftUI. Oh.. noooo...
Lets discuss how to get a Grid in SwiftUI.

Code Snippet:

struct ContentView: View {
    var body: some View {
        List {
            ForEach (0..<10) { row in
                HStack (spacing: 20) {
                    ForEach (0..<3) { column in
                        ZStack {
                            Color(.red)
                                .cornerRadius(20)
                                .onTapGesture(count: 1) {
                                        print("Selected Row\(row) & Column\(column)")
                                 }
                            Text("R\(row) - C\(column)")
                        }
                    }
                }
            }
        }
    }
}

Explanation of Code:
For this we have to take two ForEach Loops, one for drawing Rows and the other one for columns.

Steps:
1. Take a List.
2. Inside the List add a first ForEach Loop for drawing the Rows.
3. Now to add Columns in Horizontal manner add a HStack.
4. Inside this HStack add the second ForEach loop for drawing the Columns.
5. To place Text above Color I added a ZStack.
6. Inside this ZStack add the Color (and set its properties) and add the Text (to display the Row and Column number).
That's it guys we have our Grid ready. Hit the Cmd + Opt + p combination to see the preview.


Output:

Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0