开发中有时候需要计算文本的尺寸,比如在已知宽度的情况下计算高度,或者反过来知道高度计算宽度(横屏),在IOS6及之前的版本中可以使用NSString的sizeWithFont:constrainedToSize:来实现,但是IOS7中这个方法被depracated了。取而代之的是boudingRectWithSize:options:attributes:context。
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 20)];
UIFont *font = [UIFont boldSystemFontOfSize:20.0f];
label.font = font;
label.numberOfLines = 0;
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentLeft;
[label setBackgroundColor:[UIColor redColor]];
NSString *str = @"高度不变获取宽度,获取字符串不折行单行显示时所需要的高度";
NSDictionary *tdic = @{NSFontAttributeName: font};
CGSize size = CGSizeMake( 200,CGFLOAT_MAX);//如果要计算宽度就对调
size = [str boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil].size;
NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
//根据计算结果重新设置UILabel的尺寸
[label setFrame:CGRectMake(0, 10, size.width, size.height)];
label.text = str;
[self.view addSubview:label];