Search code examples
iosswiftuitableviewautolayoutnslayoutconstraint

How to resize the custom UITableViewCell to fit content?


Basically, I have a cell with 10 labels and currently I have fixed its height to 300. However, the labels might or might not have value and if the labels do not have certain value, then I need to hide them. Checking null condition for each and every label and then adjusting the height likewise is lengthy and messy. Is there any other way to achieve what I am looking for? enter image description here


Solution

  • This is an example of an idea, what I would suggest. I hope this could help you to find an optimised one for you.

    If I would assume, your data source is like this:

    // array of arrays of strings
    var Array : [[String]] = [
         ["Label1", "Label2", "Label3", "Label4"],
         ["Label1", "Label2"],
         ["Label1", "Label2", "Label3", "Label4", "Label5", "Label6"],
    ]
    

    these methods could be implemented:

    func calculateExpectedHeight(withItemsCount: Int) -> CGFloat
    {
        let titleHeight = 32.0 // this is e.g. your Layer Conf. label
        let itemHeight = 18.0 // this is for a label unit that is repeating
    
        return CGFloat(titleHeight) + CGFloat((Double(withItemsCount) * itemHeight)) + 12.0 //twelve is just for tuning
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let dataForThisRow = Array[indexPath.row]
        return calculateExpectedHeight(withItemsCount: dataForThisRow.count)
    }