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!
你的一次推荐就是对我莫大的支持。感觉不错,给个推荐或者评论吧。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 开发的设计和重构,为开发效率服务