1 #import "ViewController.h" 2 3 @implementation ViewController 4 5 - (void)viewDidLoad { 6 [super viewDidLoad]; 7 8 //根据固定的宽度计算 计算label的高度 9 [self sizeToLabelHeight]; 10 11 //根据固定的高度 计算label的宽度 12 [self sizeToLabelWidth]; 13 14 } 15 16 /** 17 * 自动计算label的宽度 前提高度固定 18 * 19 */ 20 - (void)sizeToLabelWidth 21 { 22 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; 23 label.textColor = [UIColor whiteColor]; 24 label.font = [UIFont systemFontOfSize:13]; 25 label.numberOfLines = 0; //这个属性 一定要设置为0 0表示自动换行 默认是1 不换行 26 label.backgroundColor = [UIColor blackColor]; 27 label.textAlignment = NSTextAlignmentLeft; 28 NSString *str = @"fsdfsfnksdfjsdkhfjksdhfjdolfsdfsfnksdfjsdkhfjksdhfjsdkhfjksdhfjdojdol"; 29 30 31 //第一种方式 32 // CGSize size = [str sizeWithFont:label.font constrainedToSize: CGSizeMake(MAXFLOAT,label.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping]; 33 34 //第二种方式 35 36 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; 37 attrs[NSFontAttributeName] = [UIFont systemFontOfSize:13]; 38 39 CGSize size = [str boundingRectWithSize:CGSizeMake( MAXFLOAT,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; 40 41 label.frame = CGRectMake(5, 0, size.width, 100); 42 label.text = str; 43 44 [self.view addSubview:label]; 45 } 46 47 48 /** 49 * 自动计算label的高度 前提 :宽度固定 50 */ 51 - (void)sizeToLabelHeight 52 { 53 54 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; 55 label.textColor = [UIColor whiteColor]; 56 label.font = [UIFont systemFontOfSize:13]; 57 label.numberOfLines = 0;//这个属性 一定要设置为0 0表示自动换行 默认是1 不换行 58 label.backgroundColor = [UIColor blackColor]; 59 label.textAlignment = NSTextAlignmentLeft; 60 61 NSString *str = @"fsdfsfnksdfjsdkhfjksdhfjdolfsdfsfnksdfjsdkhfjksdhfjsdkhfjksdhfjdojdol"; 62 63 //第一种方式 64 // CGSize size = [str sizeWithFont:label.font constrainedToSize: CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; 65 66 //第二种方式 67 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; 68 attrs[NSFontAttributeName] = [UIFont systemFontOfSize:13]; 69 70 CGSize size = [str boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; 71 72 label.frame = CGRectMake(100, 100, 100, size.height); 73 label.text = str; 74 75 [self.view addSubview:label]; 76 } 77 78 79 @end