Tuesday, June 23, 2015

UITableViewCell - Custom Prototype Cell in UITableView with the storyboard

This is a TableView Prototype Cell Tutorial.

0. Keep the default Auto Layout and Size Classes settings in the storyboard file inspector.

1. Drag a table view to the view controller of the storyboard and then drag a table view cell into the table view.

2. Select the table view cell and set the identifier in attribute inspector as myCellIdentifier.

3. Create a new file.  Select iOS/Source/Cocoa Touch Class and next. Name the class as MyTableViewCell and a subclass of UITableViewCell.

3. Go back to the storyboard. Select myCellIdentifier (formerly the table view cell). Select the identity inspector and select MyTableViewCell as the class.

4. Drag two labels into the prototype cell. Control-drag the labels into the MyTableViewCell.swift file.

    @IBOutlet weak var myLabel1: UILabel!
    @IBOutlet weak var myLabel2: UILabel!

5. In ViewController.swift, change the class type to UITableViewController:

class ViewController: UITableViewController {

6. Complete the ViewController.swift file as below:

import UIKit

class ViewController: UITableViewController {
    var myArray = ["AAA", "BBB", "CCC", "DDD"]
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

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

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCellIdentifier", forIndexPath: indexPath) as! MyTableViewCell
            cell.myLabel1.text = myArray[indexPath.row]
            cell.myLabel2.text = "\(indexPath.row)"
        return cell

MyTableViewCell.swift is:

import UIKit

class MyTableViewCell: UITableViewCell {

    @IBOutlet weak var myLabel1: UILabel!
    @IBOutlet weak var myLabel2: UILabel!
    override func awakeFromNib() {
        // Initialization code

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state


7. Add two images to the table cell as below:

8. Add width and height constraints to the two images:

Control-drag the top image icon to the top and select "Top Space to Container Margin".
Control-drag the top image icon to the right, and control-drag the bottom image to the right and to the bottom. Select the top option each time. 

The ViewController Scene becomes:

9. Run the app and the result is:


UITableViewCell - Create Custom Prototype Table Cell in UITableView Programmatically (without using the Storyboard)

No comments:

Post a Comment