iOS开发UILabel自适应宽度

UILabel *label = [[UILabel alloc] init];
label.text = @"jfdkgiuhuhkjkllklmmlkgfhsresresdxcvjikpok5687879hkhkg";
label.backgroundColor = [UIColor grayColor];
[self.view addSubview:label];

CGSize size = CGSizeMake(20,20); //设置一个行高上限
NSDictionary *attribute = @{NSFontAttributeName: label.font};
CGSize labelsize = [label.text boundingRectWithSize:size options:NSStringDrawingUsesDeviceMetrics attributes:attribute context:nil].size;
label.frame = CGRectMake(0, 20, labelsize.width + 3, labelsize.height);
// 系统的这个方法计算不是特别精确,所以要加3-5(不加的话,字符串长了以后label.frame.size.width会略小于字符串长度,导致文字显示不全)


你可能感兴趣的:(ios开发)