views:

96

answers:

1

I need to get the number of lines in a UILabel, so that I can move another UILabel to be at the bottom of the last line of text. I have done:

int lines = [cellDetailTextLabel.text sizeWithFont:cellDetailTextLabel.font constrainedToSize:cellDetailTextLabel.frame.size lineBreakMode:UILineBreakModeWordWrap].height /16;

but well it's not perfect because there are some cases when the UILabel is 3 lines long but the above code only returns 2, but this is not the case for all 3 lines of UILabels.

A: 

It's better to treat UILabel's text layout as a black box (it does fun things like auto-adjusting font size when the text gets too long).

Instead, consider using UIView sizing methods:

// Ask the label to shrink (or grow) until it fits its text:
[cellDetailTextLabel sizeToFit];
// Get the frame.
CGRect r = cellDetailTextLabel.frame;
// Move its origin to below cellDetailTextLabel
r.origin.y = CGRectGetMaxY(r);
// Set its size to the size of the second label
r.size = cellLabel2.frame.size;
// Finally, move the second label
cellLabel2.frame = r;

I've noticed some odd behaviour with text-sizing on iPhone 4 (occasionally labels are an extra line too high or so); I'm not sure if this is fixed in 4.1.

tc.
This is moving the detail text rather than the second label. I need the 2 labels in the vertical center of their parent view.
Jonathan