您的位置:首页 > 移动开发 > IOS开发

iOS-文字自适应

2015-12-11 19:26 393 查看
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(0, 20, 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(10);
make.top.equalTo(self.view.mas_top).with.offset(100);
}];
}


不得不再次感叹Masonry!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: