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