Dynamic UITableViewCell Height | Swift

Working as an iOS developer since iOS 4 I have been able to see lots of changes like the introduction of ARC, auto layout, storyboards, size classes and swift. Working for agencies I am always amazed at how long it takes some companies to adopt these new tools, a lot of which make your life easier and reduce the amount of code you have to write. Today I’m going to be talking about how easy it is to create a UITableViewCell that has a dynamic height based on the content in the cell using Auto Layout. If you want to follow along with project you can download the it from github. Also if you have any questions send me a tweet over at
or leave a comment below.

Setting up the UITableViewCell

First thing we do is set up the view. I have a UITableView in my view and since I’m using a storyboard I can prototype the cell right in the table view. I add two UILabels that will hold the cell’s content. Here is what we have so far:
Storyboard with UITableView and prototype cell
Next we need to add the constraints to the labels. Since we want them to resize depending on how much text is in them we are going to set leading, trailing, top, and bottom spacing constraints. The First Label will look like this:
Screen Shot 2015-04-05 at 2.19.36 PM
And the second label’s constraints will look like this:
Screen Shot 2015-04-05 at 2.22.13 PM
The constraints in Label 1 are letting the view know each label has a margin of about 8 points to the top, leading and trailing spacing and another 8 points to the label below it. So now matter how the height of the label to keep it spacing. The constraints in Label 2 are doing pretty much the same thing except the top spacing is referring to the label above it and the bottom spacing is referring to the parent view.

Don’t forget to set the number of lines in the label to 0 and line breaks to word wrap so the label can have multiple lines of text

Setting up the UITableView

In the view controller we created an IBOutlet for the table view and there is only one thing we have to do differently and it’s letting the talbe view know it will be using dynamic heights for each cell.

self.tableview.rowHeight = UITableViewAutomaticDimension 

Once that is done we just handle it like a normal UITableView and UITableViewCelll no need to sizeToFit or calculate height for heightForRowAtIndexPath! Here is what the completed ViewController looks like:

//
//  ViewController.swift
//  Dynamic-Cell-Height
//
//  Created by Barrett Breshears on 4/5/15.
//  Copyright (c) 2015 Barrett Breshears. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableview:UITableView!
    var tableViewData:[String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableview.rowHeight = UITableViewAutomaticDimension 
        
        self.tableViewData.append("Bacon ipsum dolor amet venison pork chop beef tri-tip meatball andouille. Biltong cupim turducken turkey pig, picanha shankle porchetta salami ham hock venison. Bresaola salami sausage corned beef jowl meatball spare ribs chuck short loin chicken. Bacon ham hock swine leberkas salami porchetta kielbasa shankle.")
        self.tableViewData.append("Landjaeger ham hock kevin shankle, sirloin bacon jowl meatball tail. Frankfurter ham chicken corned beef meatloaf ground round pork loin turkey tenderloin cow pork filet mignon bacon short ribs jerky. Drumstick bresaola picanha tail. Ribeye tail landjaeger, sausage pork belly biltong flank shank fatback cow meatloaf. Frankfurter short loin pancetta turkey t-bone, pork chop sirloin. Sirloin pork loin boudin spare ribs pastrami. Pig brisket sirloin chuck turkey.")
        self.tableViewData.append("Spare ribs cupim prosciutto hamburger kevin strip steak pastrami bresaola ham turducken pork kielbasa picanha. Cupim strip steak chicken pork belly beef ribs. Pork chop strip steak flank tenderloin short loin bacon corned beef cupim ground round venison doner ham chicken tail beef. Corned beef cupim tenderloin doner prosciutto filet mignon. Tail ham hock ham hamburger shankle landjaeger sirloin, brisket tongue t-bone pork. Beef ribs porchetta alcatra hamburger, chicken filet mignon ground round ham ball tip shank turducken pork chop. Ham hock venison t-bone frankfurter prosciutto, doner drumstick shankle ball tip tenderloin ribeye.")
        self.tableViewData.append("Frankfurter ham spare ribs turducken venison biltong. Tenderloin kevin flank pork loin capicola. Pastrami tenderloin kevin, turducken beef ribs salami cupim short ribs. Pork flank cupim, meatloaf tail leberkas tri-tip filet mignon tenderloin turducken beef salami.")
        self.tableViewData.append("Doner ball tip meatball shoulder tongue shankle chicken. Ground round turducken kielbasa, chicken meatloaf flank corned beef chuck rump hamburger spare ribs. Beef ribs pork belly filet mignon meatloaf, corned beef andouille tri-tip jerky turkey biltong alcatra ham hock. Alcatra meatloaf capicola, drumstick cupim spare ribs boudin meatball kevin cow ribeye porchetta beef ribs. Cupim alcatra beef pork chop pork belly ground round capicola salami turkey shankle tenderloin chicken frankfurter landjaeger. Cow hamburger meatloaf pancetta bacon rump, venison pork belly kielbasa kevin.")
    }

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

    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as? CustomTableViewCell;
        
        var data:String = self.tableViewData[indexPath.row] as String!
        cell?.label1.text = data
        cell?.label2.text = data
        
        return cell!;
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableViewData.count
    }
    

}

Thats it! I think this simple example really shows how much you can do with Auto Layout, and if you have been to busy or just more comfortable using springs and struts you consider learning Auto Layout and constraints. If you enjoyed this post I would really appreciate it if you share it with your friends. Also I am always looking for iOS developer friends follow me on twitter and send me a tweet if you ever want to talk about anything, please no android developers (just kidding).