Expand label/cell size based on text size in UITableView Swift

uitableview dynamic cell height programmatically swift 4
uitableviewcell dynamic height based on content swift
uitableviewcell height change dynamically
uitableview dynamic height swift
uitableview height based on number of cells autolayout
uitableviewcell font size swift
uitableview height based on content

I am new to iOS development. I have a problem with my cell sizing. I am not using Auto-Laylout feature. My current TableView cell looks something like this. I want to make the label size which is selected in the image to be extended dynamically based on the text content of that Label.

Thanks in advance.

i think the swift version like below, it calculates nearer values not the exact height, for example

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

 var messageArray:[String] = []
 override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.
      messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background",
                      "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.",
                      " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.",
                      "See & Dive"]

in the above we have an array which contains string of different length

 func numberOfSectionsInTableView(tableView: UITableView) -> Int
        return 1;

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    return messageArray.count;

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell;
    if(cell == nil)
        cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "CELL")
        cell?.selectionStyle = UITableViewCellSelectionStyle.none
    cell?.textLabel.font = UIFont.systemFontOfSize(15.0)
    cell?.textLabel.text = messageArray[indexPath.row]
    cell?.textLabel.numberOfLines = 0
    return cell!;

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row])
    return height + 70.0

func calculateHeight(inString:String) -> CGFloat
    let messageString = inString
    let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]

    let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

    let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

    let requredSize:CGRect = rect
    return requredSize.height

try it in a new project just add the tableview and set its datasource and delegate and past the code above and run

the result will be like below

Change the UITableViewCell Height According to Amount of Text , Based on the code you have provided, I think you are increasing only the cell *) indexPath { //minimum size of your cell, it should be single line of label if you are You need to pass the text, font and width as per your requirement. In Swift 4: Use Auto Layout Constraints to Adjust Cell Size and Spacing. At this point, the two labels are able to adjust the size of their text automatically. However, the cell isn’t able to adjust its size. Auto Layout constraints are needed to adjust the size and spacing of the cell’s contentView and the labels it contains.

Try to override methods:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension

Complete solution:

In iOS 8, Apple introduces a new feature for UITableView known as Self Sizing Cells. Prior to iOS 8, if you displayed dynamic content in table view with varied row, you need to calculate the row height on your own.

In summary, here are the steps to implement when using self sizing cells:

• Add auto layout constraints in your prototype cell

• Specify the estimatedRowHeight of your table view

• Set the rowHeight of your table view to UITableViewAutomaticDimension

Expressing last two points in code, its look like:

tableView.estimatedRowHeight = 43.0;
tableView.rowHeight = UITableViewAutomaticDimension

You should add it in viewDidLoad method.

With just two lines of code, you instruct the table view to calculate the cell’s size matching its content and render it dynamically. This self sizing cell feature should save you tons of code and time.

In Attributes Inspector of your UILabel, change Lines value to 0, so label will automatically adjust the number of lines to fit the content.

Please note that first point is required and remember that you cannot use self sizing cell without applying auto layout.

If you are note familiar with auto layout, please read this, it will be enough:


Or, easier way to set auto layout, but maybe not be what you exactly expected is to clear all of your constraints, go to Resolve Auto Layout Issues and for All Views click on Reset to Suggested Constraints.

Self-sizing Table View Cells, Drag and drop a new UILabel onto the cell, and set the text to Bio. A label with its number of lines set to 0 will grow based on how much text it is showing. Open AuteurListViewController.swift (in the ViewControllers group) and When you set the row height as UITableViewAutomaticDimension , the� In this case I’m changing text to something totally different but if we had a short and long version of the same text then change would be impossible to even notice.

Just add this in Viewdidload

tableView.estimatedRowHeight = 44.0 
tableView.rowHeight = UITableViewAutomaticDimension

Creating Self-Sizing Table View Cells, Swift; Objective-C Create table view cells that support Dynamic Type and use system spacing adjust the spacing surrounding text labels based on the text size. This property tells the label to automatically adjust the text size for its font when The width of both labels should extend to fill the width of the cell's content � How to make dynamic Height of Label as content size(text size) increase label in tableview cell Height fully automatically in swift 4. Thanks you all , Like

func calculateHeight(inString:String) -> CGFloat
           let messageString = inString
           let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue:
   NSAttributedString.Key.font.rawValue) : UIFont.systemFont(ofSize:

           let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
           let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude),
   options: .usesLineFragmentOrigin, context: nil)

           let requredSize:CGRect = rect
           return requredSize.height

How To Make Expandable UITableViewCells For Dynamic Text , Specifically, how to dynamically expand cells to reveal more content. Giving the fact Self-Sizing cells provides a way to adjust the cell height depending on the This tutorial is made using the latest Xcode 8 and Swift 3 language. Note: The key point to the label expandable feature is to allow it to contain� A UITable View Cell object is a specialized type of view that manages the content of a single table row. You use cells primarily to organize and present your app’s custom content, but UITable View Cell provides some specific customizations to support table-related behaviors, including: Applying a selection or highlight color to the cell.

How to implement dynamic height table view cell (self sizing), UIKit, Auto Layout, Swift and more When implementing a dynamic height tableview cell, one common issue we get is that the text either got clipped or two elements get overlapped Putting these two lines seems easy, but somehow the cell refuse to expand to the right height even when the label exceed� In our example, the only item you need to deal with is the label that we added. We calculate the height of the cell by determining the size of the text based on the length of the text and the font we intend to use. The NSString class provides a method called -sizeWithFont that enables us to obtain this size. The following code show how we

Automatically resizing UITableViewCells with , Automatically resizing UITableViewCells with Dynamic Type and text that matches a user's preferred size, and where every cell automatically Fortunately , iOS allows us to request automatic sizing of table view cells based on their contents. “Title” label inside the table view cell – you'll know when you have the correct� I am going to create two files as part of the model for our app, which are Contact.swift and ContactAPI.swift. Go ahead and create the contact.swift file and choose the Swift File option as it will be a UI Independent Class. This file contains a simple Contact Struct that will have a few properties in it based on the final table view cell image

Self-Sizing Table View Cells in Practice, Modern iOS apps ought to respect the user's preferred text size with Dynamic Type and be localized to reach a global audience. Self-sizing cells in UITableView and UICollectionView were added as a feature in iOS 8. Swift Objective-C iOS 10 did not increase the cell height when the built-in labels were set to use� The default value of this property is automatic Dimension, which causes the table view to choose an appropriate height based on your cell's content. If you create a self-sizing cell in Interface Builder, the table view changes the default row height to the value you set in Interface Builder.

  • check this. It's Objctive-C version
  • @Boyi Li, I am sorry I have no idea about Objective C, please help...
  • It can be done with 2 lines of code if you use auto layout. Why aren't you using that?
  • I have nearly 20 screens in my storyboard and if I use auto-layout for this screen alone, it affects the layout of all my other screens. Can you please say how to use auto-layout in this view alone ?
  • You really should be using auto layout for all your screens. Enabling auto layout is a storyboard wide thing; it's either on or off for the whole storyboard. However, you could design your cell in a xib, and use auto layout there.
  • all cells turn into short size and there is no other difference. All the contents are like merged.
  • did u tried above code in separate project, .. u need to make some modification for your requirement, above code is just to find height based on the string content . i will add screen shot how s the result
  • perhaps not the best approach. but the only one that did it for me
  • I had it all right but was missing this "In Attributes Inspector of your UILabel, change Lines value to 0, so label will automatically adjust the number of lines to fit the content." from above. That did the trick.
  • This made my day Thank you!