iOS获取Label高度的几种方法与对比

2020-01-18 18:21:11于海丽

介绍

在设置 UILabel 的 Frame 高度时,不能简单的设置为字体的 font size。否则会将字体的一部分裁剪掉。因为 UILabel 在不同的字体设置下,对 Frame 的高度要求也不一样,大多数情况下都比Font的高度设置要高一些。

一、sizeThatFits

使用 view sizeThatFits 方法。


// return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (CGSize)sizeThatFits:(CGSize)size;

例子:


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

使用 view sizeToFit 方法。

注意:sizeToFit 会改变 view 原来的 bounds,而 sizeThatFits 不会。


// calls sizeThatFits: with current view bounds and changes bounds size.
- (void)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 sizeWithAttributes 方法。


- (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs NS_AVAILABLE(10_0, 7_0);

例子


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 boundingRectWithSize 方法。


// NOTE: All of the following methods will default to drawing on a baseline, limiting drawing to a single line.
// To correctly draw and size multi-line text, pass NSStringDrawingUsesLineFragmentOrigin in the options parameter.
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);

参数的意义:

1、size

限制最大宽高, 虽然是自适应,但是需要限制最大的宽度和高度。