Search code examples
iosuitableviewautolayoutios11

Autosizing Cells Not Working in iOS 11


I am populating my UITableView from a web service. Here are all the constraints. Some of the items like Cheese Burgers has 10 lines of text which is not displayed.

enter image description here

And here is the result:

enter image description here


Solution

  • To enable automatic resizing of your UITableViewCell, set the rowHeight and estimatedRowHeight of your UITableView in your controller's viewDidLoad() method, like so:

    self.tableView.estimatedRowHeight = 150.0
    self.tableView.rowHeight = UITableViewAutomaticDimension
    

    And then if you would like or you need to implement the heightForRow UITableViewDelegate method, don't forget to pass again the UITableViewAutomaticDimension to whatever row or section that needs an auto resizing cell, like so:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let section = indexPath.section
        if let itemSection = ItemTableViewSections(rawValue: section) {
            switch itemSection {
            case .header: return 80.0
            case .photos: return 95.0
            case .note: return UITableViewAutomaticDimension
            case .rejectOptions: return 50.0
            }
        }
    
        return 0
    }
    

    Lastly, don't forget to select an answer if an answer really answers your question just like in your last question :)

    EDIT: I made a sample project that uses Storyboard and targeting merely iOS 11. All works fine. Just don't forget to set your label's constraint - top, bottom, leading, and trailing. These constraints will be required for autoresizing cell. Lastly, set the UILabel's number of lines to 0.

    enter image description here