IOS7中自动计算label的宽度和高度的方法

时间:2022-02-27 07:40:36
 #import "ViewController.h"

 @implementation ViewController

 - (void)viewDidLoad {
[super viewDidLoad]; //根据固定的宽度计算 计算label的高度
[self sizeToLabelHeight]; //根据固定的高度 计算label的宽度
[self sizeToLabelWidth]; } /**
* 自动计算label的宽度 前提高度固定
*
*/
- (void)sizeToLabelWidth
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:];
label.numberOfLines = ; //这个属性 一定要设置为0 0表示自动换行 默认是1 不换行
label.backgroundColor = [UIColor blackColor];
label.textAlignment = NSTextAlignmentLeft;
NSString *str = @"fsdfsfnksdfjsdkhfjksdhfjdolfsdfsfnksdfjsdkhfjksdhfjsdkhfjksdhfjdojdol"; //第一种方式
// CGSize size = [str sizeWithFont:label.font constrainedToSize: CGSizeMake(MAXFLOAT,label.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping]; //第二种方式 NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:]; CGSize size = [str boundingRectWithSize:CGSizeMake( MAXFLOAT,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; label.frame = CGRectMake(, , size.width, );
label.text = str; [self.view addSubview:label];
} /**
* 自动计算label的高度 前提 :宽度固定
*/
- (void)sizeToLabelHeight
{ UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:];
label.numberOfLines = ;//这个属性 一定要设置为0 0表示自动换行 默认是1 不换行
label.backgroundColor = [UIColor blackColor];
label.textAlignment = NSTextAlignmentLeft; NSString *str = @"fsdfsfnksdfjsdkhfjksdhfjdolfsdfsfnksdfjsdkhfjksdhfjsdkhfjksdhfjdojdol"; //第一种方式
// CGSize size = [str sizeWithFont:label.font constrainedToSize: CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; //第二种方式
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = [UIFont systemFontOfSize:]; CGSize size = [str boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; label.frame = CGRectMake(, , , size.height);
label.text = str; [self.view addSubview:label];
} @end