標籤:
1.自動改變Label的寬和高
1 - (void)createLabel1 2 { 3 UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; 4 label.backgroundColor = [UIColor redColor]; 5 NSString * str = @"自動改變label的寬和高"; 6 label.text = str; 7 //這句話一定要放填充字串的後面 8 [label sizeToFit]; 9 [self.view addSubview:label];10 }
2.根據文字資訊擷取
1 - (void)createLabel 2 { 3 UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; 4 label.backgroundColor = [UIColor redColor]; 5 label.font = [UIFont systemFontOfSize:30.0f]; 6 NSString * str = @"計算文本的寬和高"; 7 8 NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:30.0f]}; 9 10 //計算文本的寬高方式一:11 CGSize textSize = [str sizeWithAttributes:attributes];12 13 //計算文本的寬高方式二:14 //CGSize textSize = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;15 16 //根據計算的文本寬高重新設定label的frame值17 [label setFrame:CGRectMake(0, 20, textSize.width, textSize.height)];18 19 label.text = str;20 [label sizeToFit];21 [self.view addSubview:label];22 }
3.用Masonry布局自適應
1 - (void)createLabel2 2 { 3 UILabel * label =[UILabel new]; 4 label.backgroundColor = [UIColor orangeColor]; 5 NSString * str = @"用第三方的Masonry布局好簡單"; 6 label.textColor = [UIColor grayColor]; 7 label.text = str; 8 9 //甚至這一句都不用寫10 //[label sizeToFit];11 12 [self.view addSubview:label];13 14 //用Masonry去約束label或者button.不設定label或者button的寬高,它會自己計算的。15 [label mas_makeConstraints:^(MASConstraintMaker *make) {16 17 make.left.equalTo(self.view.mas_left).with.offset(10);18 make.top.equalTo(self.view.mas_top).with.offset(100);19 }];20 }
不得不再次感歎Masonry!
iOS-文字自適應