The bigger problem is the constraint height <= 41
. When the title doesn't fit within two lines, the titleLabel
will try to grow beyond the height of two lines (which I guess in your case is around 38?) but is then stopped at the constraint's 41
. Since this is slightly higher than the height of two lines, the top of the first line will become a few pixels lower when the lines are centered within its frame. This explains the difference between your first and third example.
A possible solution (although a storyboard only would be better) is to measure the height of the label when assigning it, and manually update the height constraint to either one or two lines of height.
cell.titleLabel.text = @"your title";
CGSize size = CGSizeMake(cell.titleLabel.bounds.size.width, 0);
size = [cell.titleLabel sizeThatFits:size];
if (size.height > lineHeight)
cell.heightConstraint.constant = lineHeight * 2;
else
cell.heightConstraint.constant = lineHeight;
The heightConstraint
is connected to your height constraint, which you need to change to =
type. To calculate the lineHeight
you can (for example) assign a short constant string to the label when initializing, then measure it.
As for the difference between the first and the second example I do not really have any solution, except adding a constant to the else statement above. Yes, it's ugly and would need testing on different devices to see if it works. Or maybe you can live with 1 pixel difference...?