下面分两种情况考虑:
1、UILabel宽度不变,根据字体多少,自动调整UILabel的高度,并折行显示。
代码如下:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 20)];
label.font = [UIFont boldSystemFontOfSize:20.0f]; //UILabel的字体大小
label.numberOfLines = 0; //必须定义这个属性,否则UILabel不会换行
label.textAlignment = NSTextAlignmentLeft; //文本对齐方式
//宽度不变,根据字的多少计算label的高度
NSString *str = @"可以更改此内容进行测试,宽度不变,高度根据内容自动调节";
CGRect rect = [str boundingRectWithSize:CGSizeMake(100, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size]} context:nil];
//根据计算结果重新设置UILabel的尺寸
[label setFrame:CGRectMake(0, 10, 200, rect.size.height)];
label.text = str;
[self.view addSubview:label];
上述为代码方式创建的label,而在一些开发中使用了约束时而lable中的字数又不确定时,可以用boundingRectWithSize:options:attributes:context:这种方法得到rect.size.height后,来①修改label的高度的约束。②若label在cell中,可以通过返回rect.size.height+别的控件的高度来实现cell的高度。
2、UILabel高度不变,根据字体多少,自动调整UILabel的宽度,并折行显示
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
label.font = [UIFont boldSystemFontOfSize:20.0f]; //UILabel的字体大小
label.numberOfLines = 0; //必须定义这个属性,否则UILabel不会换行
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentLeft; //文本对齐方式
[label setBackgroundColor:[UIColor redColor]];
//高度固定不折行,根据字的多少计算label的宽度
NSString *str = @"高度不变获取宽度,获取字符串不折行单行显示时所需要的长度";
CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, label.frame.size.height)];
NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
//根据计算结果重新设置UILabel的尺寸
[label setFrame:CGRectMake(0, 10, size.width, 20)];
label.text = str;
[self.view addSubview:label];
项目中发现,以上使用的计算宽度的方式,已经过期,会有警告,再次搜索后发现,可使用方法:
- (CGRect)frameWith:(UILabel *)child
{
CGRect frame = child.frame;
CGSize newSize;
if (iOS7) {
newSize = [child.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:child.font,NSFontAttributeName, nil]];
}else
{
newSize = [child.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:child.font, nil]];
}
CGRect newFrame = CGRectMake(frame.origin.x, frame.origin.y, newSize.width, newSize.height);
return newFrame;
}
比如计算label的宽度,可以
CGRect labelSize = [self frameWith:label];
label.frame = labelSize;
其中两种情况,核心代码均为size处的代码,均要把对应的size设置为MAXFLOAT