DEV Community

Umesh Verma
Umesh Verma

Posted on

Create a grid view in iOS using Swift.

We will see how to achieve the grid layout by using the collection view.

Screenshot 2021-01-20 at 11.36.19 AM

Let's create a starter project from Xcode.
go to File -> New -> Project

Screenshot 2021-01-20 at 10.56.15 AM

Now select app then clicks on next and add your project name then create.

Next open the Main.storyboard and add a collection view in your view controller.

Add the required constraints to this collection-view.

Screenshot 2021-01-20 at 10.59.12 AM

Next select the collection view and set min spacing for cell and line both from the default value to 0 because we will set it from code.

Screenshot 2021-01-20 at 11.04.52 AM

Now jump to the ViewController, and add an IBOutlet connection from the storyboard collection view to this view controller.



import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var gridCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpCollectionView()
    }
}


Enter fullscreen mode Exit fullscreen mode

Let's do some modification to the collection view



private func setUpCollectionView() {
     /// 1   
     gridCollectionView
            .register(UICollectionViewCell.self, 
             forCellWithReuseIdentifier: "cell")

     /// 2
     gridCollectionView.delegate = self
     gridCollectionView.dataSource = self

     /// 3
     let layout = UICollectionViewFlowLayout()
     layout.scrollDirection = .vertical
     /// 4
     layout.minimumLineSpacing = 8
     /// 5
     layout.minimumInteritemSpacing = 4

     /// 6
     gridCollectionView
           .setCollectionViewLayout(layout, animated: true)
   }


Enter fullscreen mode Exit fullscreen mode
  1. Register a default cell for collection view.
  2. Set the delegate actions to the current view controller.
  3. Create a custom flow layout for this.
  4. Set a minimum line spacing with your padding
  5. Set the minimum interim-item spacing half of the line-spacing.
  6. Set this custom layout to the collection view.

Next add the data source to the current view controller.


 swift
extension ViewController: UICollectionViewDataSource {
    /// 1
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    /// 2
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        /// 3
        cell.backgroundColor = .randomColor()
        return cell
    }
}


Enter fullscreen mode Exit fullscreen mode
  1. Set the number of items in the collection view. We didn't add the number of sections so it will assign the default value to 1
  2. dequeueReusableCell with the given cell identifier from setupCollectionView method.
  3. Setting the background color with a Random Color.

Now let's assign the delegate



extension ViewController: UICollectionViewDelegateFlowLayout {
    /// 1
    func collectionView(_ collectionView: UICollectionView, 
                  layout collectionViewLayout: UICollectionViewLayout,
                  insetForSectionAt section: Int) -> UIEdgeInsets {
        /// 2
        return UIEdgeInsets(top: 1.0, left: 8.0, bottom: 1.0, right: 8.0)
    }

    /// 3
    func collectionView(_ collectionView: UICollectionView,
                   layout collectionViewLayout: UICollectionViewLayout,
                   sizeForItemAt indexPath: IndexPath) -> CGSize {
        /// 4
        let lay = collectionViewLayout as! UICollectionViewFlowLayout
        /// 5
        let widthPerItem = collectionView.frame.width / 2 - lay.minimumInteritemSpacing
        /// 6
        return CGSize(width: widthPerItem - 8, height: 250)
    }
}


Enter fullscreen mode Exit fullscreen mode
  1. First add the insetForSectionAt from UICollectionViewDelegateFlowLayout.
  2. Add the inset for collection view sections. I added left and right space 8 because I need to match the minimum line spacing between the cells.
  3. Add to assign the size for the cell so added the method from UICollectionViewDelegateFlowLayout
  4. Get the assigned layout from the collection view.
  5. distribute the width of cells.
  6. Return the size of each cell but make sure it should be less of line spacing.

Bonus: 🤔 How to create random colors?

💡 Use these extensions for creating the random colors.



/// Extension for random value get.
extension CGFloat {
    static func randomValue() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}
/// Extension for random color using random value.
extension UIColor {
    static func randomColor() -> UIColor {
        return UIColor(
           red:   .randomValue(),
           green: .randomValue(),
           blue:  .randomValue(),
           alpha: 1.0
        )
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)