views:

157

answers:

2

Whenever an & is present on the text, getting the height seems to be off all the time. Both functions return less than the actual height:

CGSize labelSize = [nameLabel.text sizeWithFont:nameLabel.font constrainedToSize: CGSizeMake( actualWidth, MAXFLOAT ) lineBreakMode:UILineBreakModeWordWrap];

CGRect textSize = CGRectMake(0.0, 0.0, 320.0, FLT_MAX);
nameLabel.frame = [nameLabel textRectForBounds:textSize limitedToNumberOfLines:0];

None of them would return the correct height though the 2nd method using textRectForBounds returns a much closer actual height. The former would return 240 but the later would return 700. The actual is 750.

This messes up my UITableView showing texts that are overlapping on top of each other.

Interestingly, the would return the same height as long as the text does not contain any & character.

Can someone enlighten me please as for the life of me I don't understand what's going on in here and know how to fix this correctly.

Thanks so much in advance.

+1  A: 

-textRectForBounds:limitedToNumberOfLines: should not be called directly (note the docs). So it's not certain to be correct. It also points out that "labels in UITableViewCell objects are sized based on the cell dimensions, and not a requested size."

I suspect that actualWidth in your call to sizeWithFont:constrainedToSize:lineBreakMode: is wider than you expect, such that the line is not actually wrapping. How are you calculating actualWidth?

You may want to replace this with sizeWithFont:forWidth:lineBreakMode: which is specifically for what you're trying to do. That said, it may just be a wrapper around the call you're making.

Rob Napier
A: 

I just had the same issue. I ended up escaping the & character and changing it to & and everything worked fine. The UILabel was smart enough to display the escaped & properly and the size was properly calculated.

Colin