Question

I just ran into to strange problem, I have a custom tableview cell with a dynamic height. While testing this all seemed to work fine, but now that I'm loading real content into it there seem to be some problems.

It appears that some text doesn't trigger a new line in a UILabel

Correct: http://dl.dropbox.com/u/274185/Screen%20Shot%202012-05-09%20at%201.15.21%20PM.png Wrong: http://dl.dropbox.com/u/274185/Screen%20Shot%202012-05-09%20at%201.15.30%20PM.png

As you can see in the wrong example, the text is pushed to the second line, but the height of the label still only counts one line.

item.project = @"Another Test Project With Longer Title (Admin / Project Management)";

item.project = @"Test Project (Admin / Project Management)";

The way I calculate the height is like this:

// when creating the cell
cell.projectLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.projectLabel.numberOfLines = 0;
[cell.projectLabel sizeToFit];

// in heightForRowAtIndexPath()
CGSize projectHeight = [item.project sizeWithFont:[UIFont boldSystemFontOfSize:13.0f] constrainedToSize:CGSizeMake(320.0f, CGFLOAT_MAX) lineBreakMode: UILineBreakModeWordWrap];

I tried changing the lineBreakMode, but this doesn't seem to help much

EDIT: It appeared to be a problem when calculation the height of the text, I used a fixed 320 points, which isn't correct, after using the actual width the height was calculated correctly.

CGSize projectHeight = [item.project sizeWithFont:[UIFont boldSystemFontOfSize:13.0f] constrainedToSize:CGSizeMake(cell.projectLabel.bounds.size.width, CGFLOAT_MAX) lineBreakMode: UILineBreakModeWordWrap];
Was it helpful?

Solution

I believe that sizeToFit only sizes the view down. You should set the frame of your label to be high enough for two lines and then call sizeToFit. That will shrink the label when the text is only one line but keep its height when the text is two lines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top