sizeWithFont返回随机值

时间:2012-06-25 08:57:44

标签: ios cocoa-touch ios5

我正在尝试根据内容的内容计算tableview中单元格的必要高度。这是- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

然而,有时sizeWithFont返回0.我无法弄清楚这是怎么可能的,因为所有参数都是硬编码的,除了一个,我可以看到该参数没有改变。

NSString *address = [properties objectAtIndex:1];

CGFloat calculatedSize = [address sizeWithFont:[[UIFont alloc] fontWithSize:15.f] constrainedToSize:CGSizeMake(207.f, 100.f) lineBreakMode:UILineBreakModeWordWrap].height;

NSLog(@"Calculated size for %@: %f", address, calculatedSize);

calculatedSize += 19.f;

return calculatedSize;

这是输出,如果我多次来回看几次尝试这个:

Calculated size for 1234 Fake St: 0.000000
Calculated size for 1234 Fake St: 0.000000
Calculated size for 1234 Fake St: 0.000000
Calculated size for 1234 Fake St: 38.000000
Calculated size for 1234 Fake St: 0.000000
Calculated size for 1234 Fake St: 38.000000

2 个答案:

答案 0 :(得分:3)

替换:

[[UIFont alloc] fontWithSize:15.0f]

使用:

[UIFont systemFontOfSize:15.f]

答案 1 :(得分:0)

我对此进行了测试并且有效

NSString *address = @"Sample text Sample text Sample text Sample text Sample text Sample text Sample text";

CGFloat calculatedSize = [address sizeWithFont:[UIFont systemFontOfSize:15.0] 
                             constrainedToSize:CGSizeMake(207.f, 100.f) 
                                 lineBreakMode:UILineBreakModeWordWrap].height;    

NSLog(@"Calculated size for %@: %f", address, calculatedSize); //String... 76.000000