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!