最近一直再考虑label的纯代码,自动调节尺寸,后来查资料找到如下方法
有两种情况
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)];
- label.text = str;
- [self.view addSubview:label];
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];
其中两种情况,核心代码均为size处的代码,均要把对应的size设置为MAXFLOAT,大家可以试试