CollectionView Using Swift

iOS Tutorials: UICollectionView Output

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit complex in UITableView. Here we will demonstrate how to create a CollectionView.

Create a simple Application or just download a starter Application from the link.

Get started with CollectionView (UICollectionView)

If you run the Sample Project downloaded from the above link, it will look something like this.

iOS Tutorials: Hello World.
iOS Tutorials: Hello World.
  • First of all, delete the “Hello World” label.
  • Now we are going to create a simple UICollectionView.
  • Firstly navigate to the main.storyboard file and delete the label which is present at the centre of the screen.

This is how now your storyboard should look like.

iOS Tutorials: main.storyboard file
main.storyboard file
  • From the objects section in the utility panel, search for UICollectionView.
  • Drag and drop theCollectionView from the panel into the empty space as indicated in the image below.

 

iOS Tutorials: Using UICollectionView
Using UICollectionView
  • Now set the frame for this CollectionView, for this in the Utility Panel (Top right corner) select the second option from right called as the “Size inspector”.
  • Put the values as (x=0, y=20, width=375, height=647)
    • Y=20, because we need to consider the safe area as well for iPhoneX.
    • Width=375 because we have selected iPhone8.
    • Height=647 because the total physical height of the device is 667. So,647 (CollectionView height) +20 (safe area).
  • Hit enter after setting the values.

 

iOS Tutorials: Set Frame UICollectionView
Set Frame UICollectionView
  • Set Constraints, as shown in the image below.
    • The “Add New Constraints” dialog will not have 4 red markers at the beginning, after selecting it will look like the image below.

 

iOS Tutorials: Set Constraints UICollectionView
Set Constraints UICollectionView
  • Set the delegate and data-source for UICollectionView to the UIViewController Object.
    • You need to select theCollectionView and then –> Right Click –> Drag to the ViewController object –> releasing the click will show a popup with options. We can select one at a time, select data-source, and repeat the same for selecting delegate as well or vice versa.

 

iOS Tutorials: UICollectionView set delegate and dataSource
UICollectionView set delegate and dataSource

 

iOS Tutorials: UICollectionView set delegate and dataSource
UICollectionView set delegate and dataSource
  • Select the last option in the Utility panel (top right corner), called as the connections inspector; make sure it looks like this.

 

iOS Tutorials: UICollectionView Utility Panel
UICollectionView Utility Panel

Note: As you can see there a default cell provided, we need to give that cell an identifier, with the help of which we can use this cell in our code. Please give the identifier for the cell as “cellIdentifier”

This identifier could be any string, but make sure it should be unique.

  • Select the cell, in the CollectionView, go-to “Attribute Inspector” and in the identifier box, provide the identifier as “cellIdentifier“.

 

iOS Tutorials: UICollectionView Cell identifier String
UICollectionView Cell identifier String
  • Now we will create an outlet, which will act as an object of the CollectionView.
  • We will now switch to assistance editor mode. (2 views will be opened).

 

iOS Tutorials: UICollectionView creating outlets
UICollectionView creating outlets
  • Creating an outlet, in the ViewController.swift file

 

iOS Tutorials: UICollectionView creating outlets
UICollectionView creating outlets
  • Name the object of CollectionView as collectionViewList, this name will be used for accessing theCollectionView.

 

iOS Tutorials: UICollectionView naming outlets
UICollectionView naming outlets
  • We will now move on to write some code and see what all things are required for actually get the CollectionView working.
  • Close the assistant editor and now, switch to ViewController.swift file where we can see the import UIKit statement and below that; class initialisation of FirstViewController as a subclass of UIViewController.
  • We will add protocol’s UICollectionViewDelegate and UICollectionViewDataSource.
  • It will give the following error; stating some required methods needs to be implemented in the class, which is going to adopt the protocols.

 

iOS Tutorials: UICollectionView set delegate and dataSource
UICollectionView set delegate and dataSource
  • Clicking on “Fix” will add the 2 methods in the code automatically.
  • We will complete the implementation of the methods, replace the 2 methods with following below-mentioned code.
    • We have added 2 more methods apart from the 2 required methods.
    • just replace the code, which has been provided below from the 2 methods.
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
// MARK: - UICollectionView Delegate/DataSource Methods
 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionCell: UICollectionViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
if indexPath.row % 2 == 0 {
collectionCell.contentView.backgroundColor = UIColor.red
}else if indexPath.row % 3 == 0 {
collectionCell.contentView.backgroundColor = UIColor.cyan
} else {
collectionCell.contentView.backgroundColor = UIColor.green
}
return collectionCell
}
 
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
showAlert(withTitleAndMessage: "Alert!", message: String(format: "%@ row is selected.",String(indexPath.row)) )
}
 
func showAlert(withTitleAndMessage title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}

 

  •  Now run the project (Command + R), to see the output. The output will be as shown below.

 

iOS Tutorials: UICollectionView Output
UICollectionView Output
  • Click on any of the item.

 

iOS Tutorials: UICollectionView Item Clicked
UICollectionView Item Clicked

Hope! this article helped, please download the whole project from the link here.

Author: Chandra.rao

iOS Developer. #Life of an developer.... Learn New technology, Code, Learn New Technology, Code, Death.