Skip to content
Join us for Free for Full Access to site Content

How to create Self-Sizing Table View Cells (Swift)

In iOS, you can use Auto Layout to define the height of a table view cell. In this tutorial, we will show you how to make your Table View Cells self-sizing.

Firstly, create a simple TableView, that belongs to your ViewController.

Create custom TableViewCell class named: QuoteTableViewCell. Open ViewController in a StoryBoard and add CellID as a tableViewCell Identifier.

Add two labels named quoteLabel and authorLabel to your custom Cell. Add constraints to them. Setup IBOutlets for these labels in QuoteTableViewCell class.

Our app will show quotes. Let’s say we have the following data with quotes, that we want to represent in our TableView. Add dataForTableView variable in your ViewController.

let dataForTableView = [(“I have not failed. I’ve just found 10,000 ways that won’t work.”,”Thomas A. Edison”), (“A man is but the product of his thoughts. What he thinks, he becomes.”,”Mahatma Gandhi”), (“Amateurs sit and wait for inspiration, the rest of us just get up and go to work.”,” Stephen King”), (“Wisdom is not a product of schooling but of the lifelong attempt to acquire it.”,”Albert Einstein”)]

 

Let’s setup our TableView. Our ViewController Will contain the following code:

//
// ViewController.swift
// SelfSizingTableViewCells
//
// Created by AppMakers.Dev Team 
//
 
import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 
 
 @IBOutlet weak var tableView: UITableView!
 
 let dataForTableView = [(“I have not failed. I’ve just found 10,000 ways that won’t work.”,”Thomas A. Edison”), (“A man is but the product of his thoughts. What he thinks, he becomes.”,”Mahatma Gandhi”), (“Amateurs sit and wait for inspiration, the rest of us just get up and go to work.”,” Stephen King”), (“Wisdom is not a product of schooling but of the lifelong attempt to acquire it.”,”Albert Einstein”)]
 
 override func viewDidLoad() {
 super.viewDidLoad()
 // Do any additional setup after loading the view, typically from a nib.
 
 self.tableView.delegate = self
 self.tableView.dataSource = self
 
 }
 
 override func didReceiveMemoryWarning() {
 super.didReceiveMemoryWarning()
 // Dispose of any resources that can be recreated.
 }
 
 // Delegate and Datasource methods of a tableView
 
 
 
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
 return 100
 }
 
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 
 let cellIdentifier = “CellID”
 
 let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? QuotesTableViewCell
 
 cell?.quoteLabel.text = self.dataForTableView[indexPath.row].0
 cell?.authorLabel.text = self.dataForTableView[indexPath.row].1
 
 return cell!
 
 }
 
 func numberOfSections(in tableView: UITableView) -> Int {
 return 1
 }
 
 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 return self.dataForTableView.count
 }
 
 
}

 

 

Let’s Run our App and see the result:

You can see that the quotes are clipped. Let’s fix this.

To turn Table View Cells into Self-Sizing Table View Cells do the following:

Select your quoteLabel and set the Lines value to 0:

Add these two methods to ViewController:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
 
 return UITableViewAutomaticDimension
 
 }
 
 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
 return 100
 }

Or you can add these calls in your ViewDidLoad (Optional):

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100

 

The system uses Auto Layout to calculate the row’s actual height. As Apple recommends here, lay out your table view cell’s content within the cell’s content view. To define the cell’s height, you need an unbroken chain of constraints and views (with defined heights) to fill the area between the content view’s top edge and its bottom edge. If your views have intrinsic content heights, the system uses those values. If not, you must add the appropriate height constraints, either to the views or to the content view itself.

Change the bottom constraint of the AuthorLabel from equal to Greater than or equal.

Run the App and see the result. Table View Cells are now Self-Sizing. You can see that quotes are not clipped now.

Let’s add a longer quote to our dataForTableView array. change dataForTableView variable in a ViewController to this one:

let dataForTableView = [(“I have not failed. I’ve just found 10,000 ways that won’t work.”,”Thomas A. Edison”), (“A man is but the product of his thoughts. What he thinks, he becomes.”,”Mahatma Gandhi”), (“Amateurs sit and wait for inspiration, the rest of us just get up and go to work.”,” Stephen King”), (“Wisdom is not a product of schooling but of the lifelong attempt to acquire it.”,”Albert Einstein”),(“Finish each day and be done with it. You have done what you could. Some blunders and absurdities no doubt crept in; forget them as soon as you can. Tomorrow is a new day. You shall begin it serenely and with too high a spirit to be encumbered with your old nonsense.”,”Ralph Waldo Emerson”)]

 

Now run your app again to see the result:

Back To Top
Search

Get Latest App Development News, Tips and Tutorials

* indicates required


Send this to a friend