ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit
来源:互联网 发布:mysql 查询最小的数据 编辑:程序博客网 时间:2024/05/29 19:47
1.定义一个UILable
self.view.backgroundColor =[UIColor whiteColor]; NSString *str=@"目前支持以下站点"; UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)]; //文本文字自适应大小 notice.adjustsFontSizeToFitWidth = YES; notice.text=str; notice.textAlignment=NSTextAlignmentCenter; CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero]; notice.center = CGPointMake(self.view.bounds.size.width/2, 20) ; notice.textColor=[UIColor whiteColor]; notice.backgroundColor=[UIColor blackColor]; [self.view addSubview:notice];
得到的效果如下图
自适应大小ios7以后有两种可行的方案:
1.sizeThatFits
NSString *str=@"目前支持以下站点"; UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)]; //文本文字自适应大小 notice.adjustsFontSizeToFitWidth = YES; notice.text=str; notice.textAlignment=NSTextAlignmentCenter; //使用sizeThatFit计算lable大小 CGSize sizeThatFit=[notice sizeThatFits:CGSizeZero]; //重新指定frame notice.frame=CGRectMake(0, 0, sizeThatFit.width, sizeThatFit.height); notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ; notice.textColor=[UIColor whiteColor]; notice.backgroundColor=[UIColor blackColor]; [self.view addSubview:notice];
效果图:
2.sizeToFit
NSString *str=@"目前支持以下站点"; UILabel *notice=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)]; //文本文字自适应大小 notice.adjustsFontSizeToFitWidth = YES; notice.text=str; notice.textAlignment=NSTextAlignmentCenter; [notice sizeToFit];//使用sizeToFit notice.center = CGPointMake(self.view.bounds.size.width/2, kL20) ; notice.textColor=[UIColor whiteColor]; notice.backgroundColor=[UIColor blackColor]; [self.view addSubview:notice];
效果图:
注意:1.计算lable大小的时候需要先进行lable的text赋值
2.如果要将lable居中显示的话,lable.center属性的设置必须放在设置新大小之后,不然会出现不居中的情况
3.ios7之前还有其他的方法
cgSize=[str sizeWithFont:font];
这个方法是NSString的方法,听说在ios7下使用会计算不准确
0 0
- ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit
- ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit
- sizeThatFits 和 sizeToFit区别
- sizeThatFits和sizeToFit
- iOS UILable 根据文字的多少改变UILable的大小
- sizeThatFits 和 sizeToFit的区别
- sizeToFit (自适应UILable的大小)
- sizeToFit与sizeThatFits的使用和区别
- UILabel如何使用sizeToFit进行宽高适配 和 sizeThatFits 以及实现总是顶端显示text的需求
- UILable 根据内容大小自适应高度
- 根据字体和文字来计算 UILable 的长度和大小
- iOS UIlable根据内容多行显示
- iOS UILable根据文本内容自适应高度
- UILable sizeToFit
- iOS: UILabel的adjustsFontSizeToFitWidth与 sizeToFit与sizeThatFits
- sizeThatFits and sizeToFit
- sizeThatFits and sizeToFit
- sizeThatFits and sizeToFit
- [linux内核]linux内核编程规范
- 如何将一个DIV设定成上下左右都居中?!
- springmvc+hibernate 基础查询
- java操作hbase工具类
- 那些不能错过的Xcode插件
- ios开发点滴-UILable 根据文字内容进行大小设置 sizeThatFits和sizeToFit
- 两个元素内容的交换
- Android 按两次返回键退出
- mybatis异常
- 对大数据开发经验
- boost::dynamic_bitset
- 网络安装centos
- 高效整洁CSS代码原则
- VMware虚拟机 ping出现 DUP!