UILabel *label = [[UILabel alloc]init];
label.text = @"要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。要多高有多高,更具字体的多少和大小来改变label的高度。";
label.numberOfLines = 0;//设置0表示显示多行
label.font = [UIFont systemFontOfSize:18];//label的字体大小
label.backgroundColor = [UIColor redColor];//label的背景颜色
label.textColor = [UIColor blackColor];//label的字体颜色
CGRect labelRect = [label.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil] context:nil];//这是最重要的东西,必须加上。
CGFloat labelWidth = labelRect.size.width;//字体的宽度,也是label的宽度
CGFloat labelHeight = labelRect.size.height;//更具字体的高度来设置label的高度
label.frame = CGRectMake(10, 20, labelWidth,labelHeight);
[self.view addSubview:label];