在大多属性情况下,给UILabel进行动态数据绑定的时候,往往需要根据字符串的多少,动态调整UILabel的宽度或高度。
下面分两种情况考虑:
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.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentLeft; //文本对齐方式
[label setBackgroundColor:[UIColor redColor]];
//宽度不变,根据字的多少计算label的高度
NSString *str = @"可以更改此内容进行测试,宽度不变,高度根据内容自动调节";
CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
//根据计算结果重新设置UILabel的尺寸
[label setFrame:CGRectMake(0, 10, 200, size.height)];