Tutorial – UICollectionview with custom cell
To start create a blank XCode project as a single view application. Once done go to the Main.Storyboard so we can add the collection view controller. From the object library in the bottom right do a search for Collection View, once found drag it to your blank storyboard to add it.
Once added we need to set the constraints so the collection view fulls up the whole screen on any device no matter what the orientation is. To do so click on the collection view you just dragged onto the storyboard (Ensuring it takes up the whole area) and do the following:
- Open the constraints window
- Click on each line until they are all red
- Click Add 4 constraints
This will ensure that the collection view will take up the whole screen at all times.
Now select the Cell in the storyboard, or under View->Collection View–>Cell. Once selected set the identifier name to Cell up in the top right. This is used as a reference to the Cell so we can set its content later.
Once this is setup you need to connect the Collectionview to the delegate & data source. Select the collection view and hold the control key, drag the line up to the “Viewcontrooller”, this will be just under View Controller Scene. Select datasource from the dropdown and repeat the same for delegate.
Now we need to setup the swift class that will hold some code & references for the Collection View Cell. Go File->New–>File and ensure Cocoa Touch Class is selected.
Name your class colvwCell, ensuring that the Subclass of is set to UICollectionViewCell. Go next and create the class.
Now the class is created go to the storyboard & select the cell again. At the top right set it’s custom class to colvwCell.
Now that this is setup we can setup our custom cell! You can add whatever you want to your custom cell such as labels, images, and any other objects.
In our cell we are going to add a label and image view. Drag them so they are inside the Cell (You may want to make the cell a bit bigger). Once done set the label text to white, and center it. You should see something like the following:
Now hit the assistant editor button to split the view up between the storyboard & colvwCell.swift. If the colvwCell is not shown by default on the right side select it from the drop down at the top.
Now we need to connect our label and image view up to our colvwCell swift class. To do this hold in the control key once the label & image view is selected and drag them to inside the colvwCell on the right hand side.
Create an outlet for both the image and label. Name the label one lblCell and the image one imgCell. Once this is done close down the split view and open Viewcontroller.swift.
After the class add UICollectionViewDataSource and UICollectionViewDelegate as follows:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
Now under class view controller add two arrays as follows – tableData stores the names of cars & tableImage stores image names of the cars. You will need to have some .jpg images names exactly the same in your XCode project for them to work. Simply download some from Google – and ensure they are named exactly the same as below (Note they are case sensitive)
var tableData: [String] = ["Evo X", "458", "GTR"] var tableImages: [String] = ["evox.jpg", "458.jpg", "gtr.jpg"]
Next up is to add our code for the Collectionview Methods
// 1 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tableData.count } // 2 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: colvwCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! colvwCell cell.lblCell.text = tableData[indexPath.row] cell.imgCell.image = UIImage(named: tableImages[indexPath.row]) return cell } // 3 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("Cell \(indexPath.row) selected") }
The code does the following:
//1
This returns the number of items in tableData to the collection view.
//2
This sets up the cell from colvwCell. Once setup it sets the cell label text and image to the relevant items in the tableData and tableImages array.
//3
This code is run whenever the user taps on a cell.
Now that this is done you can run your app and see the collection view – you should see something like the following:
If you rotate the phone the collection view will also adapt to the new layout, it will also adapt to different sized devices. If you wish to test this simply add more items in the tableData & tableImages array to fill up the screen with items in the cells.