number of lines in UILabel
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 o开发者_如何学Gonly returns 2, but this is not the case for all 3 lines of UILabels.
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.
精彩评论