根据文字多少自动设置UILabel的宽度高度

准备在视图中间显示一个label,宽度高度由要显示的文字决定。
hintView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, parentView.frame.size.width - 20, parentView.frame.size.height - 20)];

hintView.backgroundColor = [UIColor grayColor];
//设置圆角
hintView.layer.cornerRadius = 10;
hintView.layer.masksToBounds = YES;
[hintView.layer setShadowOffset:CGSizeMake(2, 1)];
[hintView.layer setShadowRadius:5];
[hintView.layer setShadowOpacity:1];

//set the text label
UILabel *hintTextLabel = [[UILabel alloc] init];
hintTextLabel.frame = CGRectMake(4, 4, hintView.frame.size.width - 8, hintView.frame.size.height - 8);
hintTextLabel.font = [UIFont boldSystemFontOfSize:20.0f];
hintTextLabel.backgroundColor = [UIColor clearColor];
hintTextLabel.textColor = [UIColor blackColor];
hintTextLabel.numberOfLines = 0; //必须定义这个属性,否则UILabel不会换行。this is used to determine how many lines this label will have.if =3,it means this label's text will show 3 lines.if =0 ,it means that this label's text will show the line whate it needs.no limit.
hintTextLabel.textAlignment = UITextAlignmentCenter; //文本对齐方式 居中

//根据字的多少计算label的宽度,宽度超过最大宽度后自动折行
CGSize hintTextLabelSize = [hintText sizeWithFont:hintTextLabel.font constrainedToSize:CGSizeMake(hintTextLabel.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
//根据计算结果重新设置UILabel的尺寸
[hintTextLabel setFrame:CGRectMake(4, 4, hintTextLabelSize.width, hintTextLabelSize.height)];
hintTextLabel.text = hintText;

[hintView addSubview: hintTextLabel];
[hintTextLabel release];

//根据label的size重新计算hintView的frame大小,并且在屏幕居中显示
hintView.frame = CGRectMake((parentView.frame.size.width - hintTextLabelSize.width) /2 , (parentView.frame.size.height - hintTextLabelSize.height) / 2, hintTextLabelSize.width + 8, hintTextLabelSize.height + 8);

[parentView addSubview:hintView];

原文地址:https://www.cnblogs.com/nanoCramer/p/3069789.html