How to use CollectionView in Swift

October 25, 2017

In this tutorial we will see how we can use UICollectionView in Swift for iOS app development

UICollectionView is very similar to the UITableView. UICollectionView can show multiple columns and it supports horizontal scrolling

Now we will build simple app to understand UICollectionView

(1) First create a single view application using XODE

(2) Now you can drag and drop the UICollectionView controller in to the View Controller of the storyborad

In this image you can see the UICollectionViewCell inside the UICollectionView. This can be seen at top left corner of the UICollectionView. You have to give value for identifier for this UICollectionViewCell

Select the UICollectionViewCell and then select the Attribute Inspector to give name for the identifier

(3) Add UICollectionViewDelegate and UICollectionViewDataSource Protocols
To work with UICollectionView, you need to add two protocols named UICollectionViewDelegate and UICollectionViewDataSource

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
   override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

(4) Conform Protocols
Now you have to conform protocol.
At a minimum, all data source objects must implement the collectionView(_:numberOfItemsInSection:) and collectionView(_:cellForItemAt:) methods.

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
 }

So this method will return the number of items which collection view should have

And the following method will return the UICollectionViewCell. This method gets the UICollectionViewCell from the ReuseIdentifier whic you defined in Step 2. Also I have changed the color of the background of the cell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as UICollectionViewCell
        
        cell.backgroundColor = UIColor.darkGray
        
        
        return cell
    }

(5) Build and Run the Application
Now you can build and run the application to get the following screen

UICollectionView Screen