iPhone sizewithfont无效?

3

I have the following code:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *currentMessage = [FeedMessages objectAtIndex:indexPath.row];

NSLog(currentMessage);

UIFont *font = [UIFont systemFontOfSize:14];

NSLog([NSString stringWithFormat:@"Height: %@",[currentMessage sizeWithFont:font forWidth:270 lineBreakMode:UILineBreakModeWordWrap].height]);

return [currentMessage sizeWithFont:font forWidth:270 lineBreakMode:UILineBreakModeWordWrap].height;
}

有人能告诉我为什么"[currentMessage sizeWithFont:font forWidth:270 lineBreakMode:UILineBreakModeWordWrap].height"总是返回null或nil吗?

我已经检查并确认currentMessage被正确填充了。

有任何想法吗?


这里肯定有一个问题,就是你在使用 %@ 格式说明符来表示浮点数。如果改用 %f 会得到什么结果? - warrenm
4个回答

7

请阅读以下问题。它描述了-您必须使用CGFLOAT_MAX或查看以下代码(从那里获取)。

 NSString *text = @"A really long string in here"; 
 CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
 NSString *stringHeight = [NSString stringWithFormat:@"%f", theSize.height];

0
我在这个问题上花了2个小时,非常烦恼。对我来说,问题出在一个如此微小和愚蠢的事情上:我开启了“发布”模式。因此,在使用调试器时,它会停在正确的代码行(不知道为什么调试器在发布模式下要这样做),但没有显示我期望的内容。

0

您没有正确使用NSLog()。应该是NSLog(@" %@",[NSString stringWithFormat:@"Height: %f",[currentMessage sizeWithFont:font forWidth:270 lineBreakMode:UILineBreakModeWordWrap].height]);

并且%f应该用于浮点数。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接