標籤:
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)sizeToLabelWidth21 {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)sizeToLabelHeight52 {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
IOS7中自動計算label的寬度和高度的方法