【问题标题】:Iphone sizewithfont doesn't work?Iphone sizewithfont 不起作用?
【发布时间】:2010-07-15 05:17:16
【问题描述】:

我有以下代码:

- (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 会得到什么结果?

标签: iphone text sizewithfont


【解决方案1】:

完成这个问题。它描述了 - 您必须使用 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];

【讨论】:

    【解决方案2】:

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

    和 %f 应该用于浮点数。

    【讨论】:

      【解决方案3】:

      除了上面提到的有缺陷的类型杂耍之外, sizeWithFont:forWidth:lineBreakMode: 仅测量(截断的)第一行的尺寸,这很奇怪。

      您想使用 sizeWithFont:constrainedToSize:lineBreakMode: 实际上将文本拆分为行并考虑行。使用 CGSizeMake(270.0f,999999.0f) 获取文本的完整高度。

      http://developer.apple.com/iphone/library/documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html

      【讨论】:

        【解决方案4】:

        我在这上面花了 2 个小时,吓坏了。对我来说,问题出在一件如此小而愚蠢的事情上:我打开了“释放”模式。因此,当使用调试器时,它会在正确的代码行处停止(不知道为什么调试器应该在发布模式下这样做),但没有显示出我的预期。

        【讨论】:

          猜你喜欢
          • 2010-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-07
          • 2012-02-19
          相关资源
          最近更新 更多