How to use TableView and CollectionView in Swift – XSTutorials

How to use TableView and CollectionView in Swift

PLEASE NOTE: This tutorial has been written using XCode 10 and Swift 5

In this tutorial, you will learn how to handle the delegate functions of an UITableView and an UICollectionView, reload data and create a custom reusable Cell.

The Xcode project

Let’s open a blank Xcode project, select Single View App, give it the name you wish, set the Organization identifier as you wish, choose Swift as language and click the Next button. Save this project on your Desktop or in any folder you wish.

In order to make this app work on older devices, set the Deployment Target as 9.0 and check the Requires full screen option in the General tab in Xcode

The app design – TableView

Open the Main.storyboard file from the left panel, that’s the interface where you will place your Views and design your app’s look. With Xcode 10, the device layout you will get is of an iPhone XR, but you’re free to select any device by clicking the View as: iPhone Xr button on the bottom of the window.

I usually choose the iPhone SE layout, so I’ll make sure that my design will work fine on all devices. I also disable Autolayout and use the Size inspector panel to set Views margins and size.

So now let’s start by dragging an UITableView into our Controller and declare its IBOutlet in the ViewController.swift file. In order for you to do that, click the Library button on the top-right corner of the Xcode window and type “tableview” in the search field of the popup that will show up, then drag and drop it.

Add a UITableView to the Controller

Adjust the TableView size to fit the screen – although first place its top edge to the 84 Y position – and set all its margins in the Autoresizing section of the Size inspector.

Set size and margins of your TableView

Right-click (or ctrl+click) and drag the indicator from the TableView to the ViewController‘s icon on the top of the screen preview. Select the dataSource option, then repeat the drag and select delegate. They are important because the app will call certain functions to fetch and display data in the UITableView.

Attach TableView’s delegate and dataSource to the ViewController

Add a prototype cell by typing 1 in the Prototype Cells field of the Attributes inspector panel.

Create a new Cell

Now select the newly created empty cell from the TableView and set its Identifier as “myCell“. Make sure that Style is set to Custom.

Assign an ID to the Cell

Drag a UILabel into your UITableViewCell, and adjust its size and margins from the Storyboard and Size inspector.

The code

It’s time to split the screen and declare our TableView in the ViewController.swift file as an IBOutlet, so click the Assistant editor button.

Show the Assistant editor in Xcode

Right-click over the TableView (or ctrl+click) and drag the blue line to the top of the override func viewDidLoad() function. Then, in the little popup, type myTableView and hit Enter – or the Connect button.

Connect the TableView to the Swift file

We have to instantiate a UITableViewCell class below the import UIKit statement, so grab this code and paste it in your Swift file:

class MyCell: UITableViewCell {
    
}

Select your Cell in the Storyboard, open the Identity panel and type MyCell in the Class field, then hit Enter.

Set the Class name to the Controller

Connect the UILabel inside the Cell and call it myLabel.

Declare the cell’s Label

We now need to create an Array that will store a few items of type String. Such strings will be shown in our TableView, so paste this code right below the myTableView declaration:

let myArray = [
    "The Lion King",
    "Avengers - Endgame",
    "Pretty Woman",
    "Blade Runner",
    "Home alone",
    "Fight Club",
    "Psycho",
    "Taxi Driver"
]

Let’s also add two delegate protocols to the ViewController‘s class declaration: UITableViewDataSource and UITableViewDelegate.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

At this point, Xcode may popup an error alert that says:

Type 'ViewController' does not conform to protocol 'UITableViewDataSource'

Don’t worry, we’ll fix it right away, here’s the code you have to paste below the viewDidLoad() function’s closure:

func numberOfSections(in tableView: UITableView) -> Int {
        return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
        
    // configure cell...
        
        
    return cell
}
    
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
}

In the numberOfSections: function, we simply return 1 because our TableView has a single section.

The cellForRowAt indexPath: delegate method is where we’ll configure our custom UITableViewCell by assigning it the needed String.

In the heightForRowAt indexPath: function we set the height of the Cell – in this case, 44px.

We’ll lastly create the code to handle e Cells selection in the didSelectRowAt indexPath: method.

So let’s add this line of code inside cellForRowAt indexPath:

cell.myLabel.text = "(myArray[indexPath.row])"

Into the didSelectRowAt indexPath: function, paste the following line, it will print the selected data in the Console:

print("SELECTED CELL: (myArray[indexPath.row])")

If you run the app now and select a row, you’ll get something like this:

Showing our TableView in the app

The app design – CollectionView

Let’s see how a UICollectionView works now. You should drag a new ViewController in the Storyboard, add a new Swift file of UIViewController type, call it SecondVC and save it in the project folder. Do this in order to implement the CollectionView in another Controller instead of removing the TableView.

Open the Library window, search for “collectionview” and drag the CollectionView object into the SecondVC screen.

Select the empty Cell and type “MyCVCell” in the Identifier field of the Collection Reusable View section.

As you did for the TableView, add a UILabel into the prototype cell of your CollectionView and set its attributes, size, and position with the inspector panels on the right side of the Xcode window.

The code – CollectionView

Split the editor area with the Assistant button and instantiate the following class below the import UIKit statement:

class MyCVCell: UICollectionViewCell {
    
}

Select the MyCVCell view from the Storyboard and assign its name in the Identity inspector.

Declare your Cell in the Identity panel

Connect the Label inside that Cell to the SecondVC.swift file, name it “myLabel“.

Declare a UILabel to the Swift file

We need to attach the dataSource and delegate options to our CollectionView to the Controller in the Storyboard, as we did for the TableView. The process is the same.

Connect delegate and dataSource of the CollectionView to the Controller

In the SecondVC‘s class declaration, add 3 delegate protocol names:

UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout

Copy the myArray array form ViewController.swift file and paste it in the SecondVC.swift file, we’re going to use the same list of Strings.

let myArray = [
    "The Lion King",
    "Avengers - Endgame",
    "Pretty Woman",
    "Blade Runner",
    "Home alone",
    "Fight Club",
    "Psycho",
    "Taxi Driver"
]

It’s time to add the necessary delegate methods to handle data for our CollectionView, so paste this code below the closure of the viewDidLoad() function:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return myArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCVCell", for: indexPath) as! MyCVCell
        
    // configure cell here...
        
    return cell
}
    
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.size.width/3 - 20, height: view.frame.size.width/3 - 20)
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

}

The numberOfSections method is where we return 1 since our UICollectionView has one single section.

In the numberOfItemsInSection delegate, we pass the number of items of the myArray array.

The cellForItemAt indexPath: is the function where we’ll tell the code to display data in each cell.

The width and height of our custom Cell can be set in the sizeForItemAt indexPath: method. In this case, the app will calculate the screen’s width and show 3 columns.

Lastly, we’ll handle a Cell selection using the didSelectItemAt indexPath: delegate.

So, let’s add this line of code inside the cellForItemAt indexPath:

cell.myLabel.text = "(myArray[indexPath.row])"

You may notice that it’s exactly the one we previously used for our TableView. CollectionViews use IndexPath as well to get data for each cell.

And we’ll reuse the following line for the didSelectItemAt indexPath: function too:

print("SELECTED CELL: (myArray[indexPath.row])")

We’re done, so now make sure to move the gray arrow from the ViewController to the SecondVC screen – in order to make it as initial Controller – and run the app. You should get something like this:

The Xcode console messages on cell selection

Conclusion

That’s all for this tutorial, you have learned the basics about how to work with a UITableView and a UICollectionView in Xcode.

Hope you enjoyed this article, feel free to post comments about it.

Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉