iOS-文字自适应

时间:2023-03-09 17:10:05
iOS-文字自适应

1.自动改变Label的宽和高

 - (void)createLabel1
{
UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor redColor];
NSString * str = @"自动改变label的宽和高";
label.text = str;
//这句话一定要放填充字符串的后面
[label sizeToFit];
[self.view addSubview:label];
}

2.根据文字信息获取

 - (void)createLabel
{
UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor redColor];
label.font = [UIFont systemFontOfSize:30.0f];
NSString * str = @"计算文本的宽和高"; NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:30.0f]}; //计算文本的宽高方式一:
CGSize textSize = [str sizeWithAttributes:attributes]; //计算文本的宽高方式二:
//CGSize textSize = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size; //根据计算的文本宽高重新设置label的frame值
[label setFrame:CGRectMake(, , textSize.width, textSize.height)]; label.text = str;
[label sizeToFit];
[self.view addSubview:label];
}

3.用Masonry布局自适应

 - (void)createLabel2
{
UILabel * label =[UILabel new];
label.backgroundColor = [UIColor orangeColor];
NSString * str = @"用第三方的Masonry布局好简单";
label.textColor = [UIColor grayColor];
label.text = str; //甚至这一句都不用写
//[label sizeToFit]; [self.view addSubview:label]; //用Masonry去约束label或者button.不设置label或者button的宽高,它会自己计算的。
[label mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.view.mas_left).with.offset();
make.top.equalTo(self.view.mas_top).with.offset();
}];
}

不得不再次感叹Masonry!