Tutorial – Custom UITableView Cell
Today we are going to look at creating a custom UITableView Cell.
I am going to start off from the post here on creating a tableview to get things going. So initially my project will already be setup with a basic tableview that looks as follows:
The code in our ViewController looks like this currently:
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var tableData: [String] = ["Hello", "My", "Table"] override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableData.append("Seemu") self.tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell cell.textLabel?.text = self.tableData[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Row \(indexPath.row) selected") } }
By the end of this post we will make it so each car manufacturer has a image next to their name, we will achieve this by making a custom cell that allows us to set it up however we like.
The first thing to do is to setup our custom view for our custom cell. To do this go File->New->File. Select “User Interface” under iOS, select empty and hit next. We will save it as vwTblCell. This gives us a blank interface to play around with to create our tableview. From the bottom right corner find the Table View Cell control and drag it on to our interface. Once this is done drag a label and also UIImage onto the Table View Control we made.
It should look like the following:
Once this is done select the attributes inspector up the right hand side, for identifier type in “cell”.
Now that this is done we need to setup an accompanying class for our interface to connect the code & label and image up. Go File->New-File. Select Source under IOS and Cocoa Touch Class. Name the class TblCell and ensure it is a subclass of UITableViewCell. Go back to the vwTblCell and set the custom class to TblCell.
Now select the assistant editor to split the view . Click on the label, hold it and control and drag it into our custom TblCell class. Create a new outlet named imgCarNane. Repeat the same steps for the Car Manf Name label but name it lblCarName. It will look like the following:
Now we will add some car logo images to show in our UIImage view, you find find them on google and download them. Add them in as follows with these names, in our Images.xcassets.
Now go to the ViewController.swift and make changes to the code so it looks like the following:
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var tableData: [String] = ["Ferrari", "BMW", "Mitsubishi", "Lambo"] // 1 override func viewDidLoad() { super.viewDidLoad() // Register custom cell let nib = UINib(nibName: "vwTblCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "cell") } // 2 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableData.count } // 3 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:TblCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell cell.lblCarName.text = tableData[indexPath.row] cell.imgCarName.image = UIImage(named: tableData[indexPath.row]) return cell } // 4 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Row \(indexPath.row) selected") } // 5 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } }
The code does the following:
// 1
This sets up & loads our custom TableView Cell.
// 2
Returns the number of car manufacturers to display in the table view.
// 3
First of all this loads our custom cell & the class TblCell we made. It then sets the TblCell image and text to be the car manufacturer, remember we connected these up from our custom view!
// 4
Shows what row of the tableview was selected
// 5
When making the custom view if we resize the view in our interface builder you will notice it doesn’t keep the right size. If you want to make your table view cell bigger you must also set the height here.
Now you can run the application and you should see your custom table cells as follows:
So the table cell can be customised in any way, not just with image views and labels! You can also add buttons, text fields and many other objects to your custom cell.