我有一个奇怪的问题。我的sizeWithFont: forWidth: lineBreakMode:NSLineBreakByWordWrapping
返回了错误的值。我有一个字符串数组,需要放在一个整洁的“表”中。单元格基本上是UIView
s,其中包含UILabel
s。为了使用正确的框架分区初始化单元格视图和标签,我需要预先计算单元格的所需高度和包装器视图的总高度,因为所有单元格都将放置在另一个视图中。我的代码如下所示:
#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);
}
但是日志返回了非常奇怪的值:
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
“1125 new likes”的宽度是99,长串只有70?高度绝对应大于20或?
答案 0 :(得分:4)
Maister,发生这种情况是因为方法[item sizeWithFont: forWidth:100 lineBreakMode:]
正在考虑当单词不适合该行时,它跳转到下一行。
所以,标签(100宽度)将是这样的:
You have 23
followers
而另一个标签可以适合整个字符串:
1125 new likes
现在你可以看到我文本中这两个字符串之间的区别(考虑到最大宽度:100)。
如果你将lineBreakMode
改为Character Wrap,它可能会给第一个字符串100和99到第二个字符串。
答案 1 :(得分:4)
尝试使用[[NSString string] sizeWithFont:UIFont constrainedToSize:CGSize lineBreakMode:(NSLineBreakMode)]