iOS UILable高度自适应
适用于iOS6以后
NSString *tip = @"UILable高度自适应,UILable高度自适应,UILable高度自适应"; UILabel label_2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 30)]; label_2.font = [UIFont systemFontOfSize:15]; label_2.lineBreakMode = NSLineBreakByCharWrapping; // 设置行数 label_2.numberOfLines = 0; [label_2 setText:tip]; [self.view addSubview:label_2]; // 计算高度 CGFloat height = [tip sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(100, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping].height; // 重新改变label_2的frame CGRect rect = label_2.frame; rect.size.height = height; label_2.frame = rect;
label_2.lineBreakMode =NSLineBreakByCharWrapping;//其中lineBreakMode可选值为
linBreakMode enum{
NSLineBreakByWordWrapping = 0, //保留整个单词,以空格为边界
NSLineBreakByCharWrapping, //保留整个字符 NSLineBreakByClipping, //以边界为止 NSLineBreakByTruncatingHead, //省略开头,以省略号代替 NSLineBreakByTruncatingTail, //省略结尾,以省略号代替 NSLineBreakByTruncatingMiddle //省略中间,以省略号代替 }