Reputation: 3701
I have a weird problem. My sizeWithFont: forWidth: lineBreakMode:NSLineBreakByWordWrapping
is returning wrong values. I have an array of strings which need to be placed in a neat "table". Cells are basically UIView
s with UILabel
s in them. In order to alloc-init the cell view and the label with the right frame I need to pre-compute the desired height of the cell and the total height of the wrapper view since all cells will be placed in another view. My code looks like this:
#define kStandardFontOfSize(x) [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:x]
CGFloat size = 0.0f; //for computing the total size as cells will be placed in another view
items = [NSArray arrayWithObjects:@"You have 23 new followers", @"1125 new likes", @"Successful week with 24 new Twitter followers and 60 new email subscribers", @"1125 new tickets", nil];
for (NSString *item in items)
{
if ([item sizeWithFont:kStandardFontOfSize(16) forWidth:100 lineBreakMode:NSLineBreakByWordWrapping].height < 25)
size += 70; //either the cell will be 70 (140) pixels tall or 105 (210)pixels
else
size += 105;
NSLog(@"%f, %f, %@", [item sizeWithFont:kStandardFontOfSize(16) forWidth:100 lineBreakMode:NSLineBreakByWordWrapping].width, [item sizeWithFont:kStandardFontOfSize(16) forWidth:100 lineBreakMode:NSLineBreakByWordWrapping].height, item);
}
But the log is returning very weird values:
82.000000, 20.000000, You have 23 new followers
99.000000, 20.000000, 1125 new likes
70.000000, 20.000000, Successful week with 24 new Twitter followers and 60 new email subscribers
67.000000, 20.000000, 1125 new tickets
How is it possible that the width of "1125 new likes" is 99 and the long string is only 70? The height should definitely be greater than 20 or?
Upvotes: 1
Views: 1221
Reputation: 571
Try to use [[NSString string] sizeWithFont:UIFont constrainedToSize:CGSize lineBreakMode:(NSLineBreakMode)]
Upvotes: 4
Reputation: 269
Maister, this happens because the method [item sizeWithFont: forWidth:100 lineBreakMode:]
is considering when the word does not fit in the line, it jump to the next.
So, the labels (100 width) will be something like that:
You have 23
followers
while the other label can fit the whole string:
1125 new likes
Now you can see the difference between those two strings in my text (considering the max width: 100).
If you change the lineBreakMode
to Character Wrap, it will probably give 100 to the first string and 99 to the second.
Upvotes: 4