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.
3: Create a new file which is a base class of UITableViewCell class and name it “MultilineLabelCell”.
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.
6: Open MultilineLabelCell.xib and connect IBOutlet lblTitle to UILabel.
7: Open ViewController.swift and add below code.
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.
Run your code and you will see, cell of dynamic height based on content length.
Pingback: Multiline UILabel in UITableView with Autolayout - Tutorial - iOSTutorialJunction