Monday, 5 June 2017

Create dynamic height UITableViewCell in Swift- tutorial

Create dynamic height UITableViewCell in Swift- tutorial

Introduction to create dynamic height UITableViewCell in Swift

In this tutorial, we will learn create dynamic height UITableViewCell in Swift or how to 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, only condition is that you set up your cell constraints correctly. So let us jump to the tutorial and learn how can we create create dynamic height UITableViewCell or multi line UILabel in UITableView using swift.

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

Step 1: Create a signle 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) 
  1. AppDelegate.swift
  2. ViewController.swift
  3. Main.Storyboard

Step 2:  Open ViewController.swift and create an IBOutLet for UITableView. 

Step 3: Create a new file which is a base class of UITableViewCell class.  

Creating MultilineLabel UItableViewCell class

Step 4: Open MultilineLabelCell.xib and follow the steps as shown in 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. You can change constant value of bottom constraint to see the different scenarios and also leading, trailing, top constraint value's, so that layout will look more attractive.

Step 5: Open MultilineLabelCell.swift and create IBOulet for the UILabel, we added to the UITableViewCell class.

Step 6: Open MultilineLabelCell.xib and connect IBOutlet lblTitle to UILabel.

Step 7: Open ViewController.swift and add below code.

In the above code we created IBOutlet for UITableView, named it as tblList and set delegate and datasource for our tblList UITbaleView. Here we need to tell the default estimated row height so that it improved performance as explained by APPLE. Also telling our ViewController.swif class that we are going to implement delegate and datasource for UITableView.
                                                             As we are using custom class so it's also good place to register custom cell xib name here. By now you are seeing error in your xcode, this 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.

No comments:
Write comments