others-how to set multiline of tableviewcell and auto height of label in xcode

Problem

How to set auto height of a UILabel in xcode? How to set the multiline mode of the UILabel in xcode? Let’s do it.

Environment

  • MacOS 10.14
  • XCode 11.3
  • Swift 5

Solution

Step 1

You must set the constraints of the UILabel like following:

image-20201021205617341

  • Top
  • Bottom
  • Leading
  • Trailing

Step 2

Set the numberOfLines properties for the UILabel:

import UIKit

class MessageTableViewCell: UITableViewCell {

    @IBOutlet weak var body: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        body.numberOfLines = 0
    }

}

The numberOfLines=0 means unlimited lines of texts in the UILabel

Step 3

Set the automaticDimension for the tableview, you can do this in the UITableViewController like this:

class MessagesTableViewController: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //auto ajust the tableview cell height
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 300
        ...
    }
    ...
}

Ok, everything is done.