Search code examples
swiftheightrowtableviewcell

UITableView: automatically set height for the row and fix it with max height constant


I need automatically set the height for the row. I use

theTable.estimatedRowHeight = 60
theTable.rowHeight = UITableViewAutomaticDimension

but the height is not fixed. I need fixed height something like MAX 60 height, by default height is 40. With estimatedRowHeight the height is not fixed and when the string is long the cell takes all screen. How to fix it?


Solution

  • You will need to put all the content of table view cell in a single view (lets call it MainView) and set MainView top, leading and trailing edge constrains to container view. Also set a height constraint less than or equal to 60 with required priority. After that put your label in MainView set top, leading and trailing constrains to MainView and a bottom space to MainView constraint with high priority. Also on your label set number of lines to 0 and preferred width to explicit. This way if label content height is less than 60, MainView will shrink and that will still match height constraint of less than or equal to 60. Otherwise if content height is greater then 60 the bottom space to MainView constraint will break without causing problems since its priority is less then MainView height constraint.

    Finally override tableview delegate methods as follow

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