iOS 计算文本宽、高
#define kScreenWidth ([UIScreen mainScreen].bounds.size.width)
创建两个 UILabel 并赋值:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *widthLabel = [[UILabel alloc] init];
widthLabel.text = @"【北京高考文科状元:高考是阶层性的考试】出身外交官家庭的2017年北京高考文科状元熊轩昂说,“高考是阶层性的考试,农村地区的孩子,越来越难考上好学校。像我这种属于中产阶级的孩子,衣食无忧,家长都是知识分子,而且还生在北京这种大城市,所以在教育资源上享受得天独厚的条件,是很多外地或农村的孩子完全享受不到的……现在的状元,通俗来讲,都是家里又好又厉害的。”他的一席话激起网民热烈讨论……";
CGFloat height = [self textHeight:widthLabel.text textWidth:kScreenWidth];
widthLabel.frame = CGRectMake(0, 200, kScreenWidth, height);
widthLabel.layer.borderWidth = 1.0;
widthLabel.numberOfLines = 0;
widthLabel.font = [UIFont systemFontOfSize:12];
[self.view addSubview:widthLabel];
CGFloat labelHeight = 20;
UILabel *heightLabel = [[UILabel alloc] init];
heightLabel.text = @"北京高考文科状元:高考是阶层性的考试";
CGFloat width = [self textWidth:heightLabel.text textHeight:labelHeight];
heightLabel.frame = CGRectMake(0, 330, width, labelHeight);
heightLabel.layer.borderWidth = 1.0;
heightLabel.numberOfLines = 0;
heightLabel.font = [UIFont systemFontOfSize:12];
[self.view addSubview:heightLabel];
}
已知文本宽求高度:
- (CGFloat)textHeight:(NSString *)text textWidth:(CGFloat)width{
CGFloat stringWidth = 0;
CGSize size = CGSizeMake(width, MAXFLOAT);
if (text.length > 0) {
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
stringWidth =[text
boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}
context:nil].size.height;
#else
stringWidth = [text sizeWithFont:self.font
constrainedToSize:size
lineBreakMode:NSLineBreakByCharWrapping].height;
#endif
}
return stringWidth;
}
已知文本高求宽度:
- (CGFloat)textWidth:(NSString *)text textHeight:(CGFloat)height {
CGFloat stringHeight = 0;
CGSize size = CGSizeMake(MAXFLOAT, height);
if (text.length > 0) {
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
stringHeight =[text
boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}
context:nil].size.width;
#else
stringHeight = [text sizeWithFont:self.font
constrainedToSize:size
lineBreakMode:NSLineBreakByCharWrapping].width;
#endif
}
return stringHeight;
}
结果如图所示: