簡體   English   中英

Iphone sizewithfont不起作用?

[英]Iphone sizewithfont doesn't work?

我有以下代碼:

- (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。

有任何想法嗎?

回答這個問題。 它描述了 - 您必須使用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];

您沒有以正確的格式使用NSLog()。 它應該是NSLog(@“%@”,[NSString stringWithFormat:@“Height:%f”,[currentMessage sizeWithFont:font forWidth:270 lineBreakMode:UILineBreakModeWordWrap] .height]);

和%f應該用於浮動。

除了上面提到的有缺陷的類型雜耍之外,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

我在這上花了2個小時,嚇壞了。 對我來說問題出在這么小而愚蠢的事情上:我打開了'釋放'模式。 因此,當使用調試器時,它停在適當的代碼行(不知道為什么調試器應該在發布模式下這樣做),但沒有顯示我的預期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM