Automatically grow static table view cell height to fit label content height

Viewed 3833

Here a low quality mockup of my cell layout:

mockup

The initial height of the static cell (set in storyboard) is 80. Inside this cell are two views. The bottom view has a fix height of 40. The top view has layout constraints to align to top margin and to vertically align to the bottom view.

Inside the top view is a label (blue color) and a button (yellow color)

The label also has the constraints to align to the top of the view and to align to the bottom of the view. The idea behind that layout and constraints is that if I increase the height of the cell to 100 for example, the bottom view height stays 40 and the top view and label height is getting expanded to a height of 60.

My label has linebreak word wrapping and number of lines set to 0. What I now want is to automatically resize the cell so that the complete content of the label is getting shown when there are more than one lines. How exactly can I do that?

I tried:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 80.0;

This is not working. The cell height always stays 80 independend from the amount of lines in the UILabel.

I also tried:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}

With the same result as my first approach.

The more complex way I tried was the following:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let heightLabel = self.heightForView(text: self.lblTitle.text!, font: UIFont(name: "Helvetica Neue", size: 18)!, width: self.lblTime.width);
    let heightView = (heightLabel + (80.0 / 2));

    print("title label height \(heightLabel)");
    print("title view height \(heightView)");

    if (heightView > 80.0) {
        return heightView;
    }

    return 80.0;
}

func heightForView(text: String, font: UIFont, width: CGFloat) -> CGFloat {
    let label: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude));
    label.numberOfLines = 0;
    label.lineBreakMode = .byWordWrapping;
    label.font = font;
    label.text = text;
    label.sizeToFit();

    return label.frame.height;
}

output:

title label height 42.5
title view height 82.5

But this also does not seem to work since the other lines are not showing up, only the first line of the label.

How can I get this working?

EDIT

I guess the approach with calculating the label height will work when I know the width of the label. But how should I know it?

1 Answers
Related