Create dynamic height UITableViewCell

Create dynamic height UITableViewCell in Swift- tutorial

Create dynamic height UITableViewCell in Swift

In this tutorial, we will learn how to create dynamic height UITableViewCell in Swift. To achieve dynamic height we will create multi line UILabel in UITableView using swift language.
                                     We will use the new UITableViewAutomaticDimension property. UITableViewAutomaticDimension property is a handy thing for iOS developers as it sets the cell height automatically. The only condition is that you set up your cell constraints correctly. So let us learn, how we can create dynamic height UITableViewCell in UITableView using swift.

Steps to create the multi line UILable in UITableViewCell of the UITableView

1: Create a single view application and name it “Multi-Line-UILable”. After creating the project you will see following files contained by the project (i am mentioning only 3 files here)
  • AppDelegate.swift
  • ViewController.swift
  • Main.Storyboard
2:  Open ViewController.swift and create an IBOutLet for UITableView.
//
// MultilineLabelCell.swift
// Multiline-Uilabel
//
// Created by Aman Aggarwal on 4/13/17.
// Copyright © 2017 iostutorialjunction.com. All rights reserved.
//
import UIKit
class MultilineLabelCell: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

3: Create a new file which is a base class of UITableViewCell class and name it “MultilineLabelCell”.
Creating MultilineLabel UItableViewCell class
4: Open MultilineLabelCell.xib and follow the steps as shown in the below image sequence. Here constraints will play important role in determining  UITableViewCell height, because autolayout always consider the constraint during rendering of the content. In our case the cell will always  have 11.5 pixel space from bottom of the cell. Though, you can change constant value of bottom constraint to see the different scenarios.
5: Open MultilineLabelCell.swift and create IBOutlet for the UILabel.
//
// MultilineLabelCell.swift
// Multiline-Uilabel
//
// Created by Aman Aggarwal on 4/13/17.
// Copyright © 2017 iostutorialjunction.com. All rights reserved.
//
import UIKit
class MultilineLabelCell: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

6: Open MultilineLabelCell.xib and connect IBOutlet lblTitle to UILabel.
7: Open ViewController.swift and add below code.
//
// ViewController.swift
// Multiline-Uilabel
//
// Created by Aman Aggarwal on 4/13/17.
// Copyright © 2017 iostutorialjunction.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblList.tableFooterView = UIView.init(frame: .zero)
tblList.register(UINib(nibName: "MultilineLabelCell", bundle: nil), forCellReuseIdentifier: "identifier")
tblList.estimatedRowHeight = 44.0
tblList.delegate = self
tblList.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

In the above code, first we created IBOutlet for UITableView and named it as tblList. Secondly, we set delegate and datasource for our tblList UITbaleView. Next we need to tell the default estimated row height so that it improved performance as explained by APPLE. Finally telling our ViewController.swift class that we are going to implement delegate and datasource for UITableView.
As we are using custom class so we need to register custom cell xib name in viewdidload. By now you are seeing error in your xcode, that is because we haven’t yet implemented the delagets and datasource for uITableView.

Step 8: Below is the complete code that will produce dynamic cell height for UITableView row, as per the content displayed by UILabel.

//
// ViewController.swift
// Multiline-Uilabel
//
// Created by Aman Aggarwal on 4/13/17.
// Copyright © 2017 iostutorialjunction.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tblList.tableFooterView = UIView.init(frame: .zero)
tblList.register(UINib(nibName: "MultilineLabelCell", bundle: nil), forCellReuseIdentifier: "identifier")
tblList.estimatedRowHeight = 44.0
tblList.delegate = self
tblList.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier") as! MultilineLabelCell
cell.lblTitle.font = UIFont.init(name: "verdana", size: 12.0)
cell.lblTitle.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
if indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 4 {
cell.lblTitle.text = "Single line text"
}
if indexPath.row == 1 {
cell.lblTitle.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text."
}
if indexPath.row == 3 {
cell.lblTitle.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum"
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}

Run your code and you will see, cell of dynamic height based on content length.

1 thought on “Create dynamic height UITableViewCell”

  1. Pingback: Multiline UILabel in UITableView with Autolayout - Tutorial - iOSTutorialJunction

Comments are closed.