一、sizeThatFits
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
NSLog(@"size = %@", NSStringFromCGSize(size));
输出结果 size = {246.33333333333334, 36}
二、sizeToFit
UILabel *testLabel = [[UILabel alloc] init];
testLabel.font = [UIFont systemFontOfSize:30];
testLabel.text = @"Today is a fine day";
[testLabel sizeToFit];
NSLog(@"size = %@", NSStringFromCGSize(testLabel.frame.size));
输出:size = {246.33333333333334, 36}
三、sizeWithAttributes
NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGSize size = [text sizeWithAttributes:@{
NSFontAttributeName : font
}];
NSLog(@"size = %@", NSStringFromCGSize(size));
输出: size = {246.3134765625, 35.80078125}
四、boundingRectWithSize
NSString *text = @"Today is a fine day";
UIFont *font = [UIFont systemFontOfSize:30];
CGRect suggestedRect = [text boundingRectWithSize:CGSizeMake(800, MAXFLOAT)
options:NSStringDrawingUsesFontLeading
attributes:@{ NSFontAttributeName : font }
context:nil];
NSLog(@"size = %@", NSStringFromCGSize(suggestedRect.size));
输出: size = {200, 35.80078125}
四种方式对比
在设置字体为 30 的情况下,前两种使用 view 的方法返回 size = {246.33333333333334, 36} ,后两种使用 NSString 的方法返回 size = {246.3134765625, 35.80078125} 。使用 view 方法比使用 NSString 方法的返回的值略大。
我猜测其原因都是因为,文本渲染引擎在渲染一行文本的时候都需要在label的顶部和底部预留一小部分空间,应该是出于排版美观方面的考量。
在显示不同的 font size 的字体时,获得的字符串高度比 font size 大的值是不同的。
比如 font size 为 13 时,算出高度为 16,font size 为 20 时,算出高度为 24。
所以平常设置 UILabel 高度的时候,也不能简单的在 font height 基础之上加随意值。