iOS7.0中UILabel高度调整注意事项
转自:http://blog.csdn.net/k12104/article/details/33731833
http://herkuang.info/blog/2013/12/31/ios7%E4%B8%ADuilabel%E9%AB%98%E5%BA%A6%E8%B0%83%E6%95%B4%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/
我的“记词助手”在升级到iOS7之后,一直出现UILabel错位的问题:
我的label是用- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode 来计算的,但是似乎计算得不是很正确。
实际上UILabel的frame是红框的大小,但是在宽度不够的时候,不知道触发了什么bug,这个Label在绘制的时候文字会被挤下去。这个问题到底是什么,我也没搞清楚,但是增加UILabel的宽度后,就会显示正常。
在跟了一遍代码后发现,在iOS7下面,- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode这个函数返回的值是带小数的,设给UILabel的frame之后,UILabel的宽度就小于文字绘制需要的宽度了。就会造成上面的问题。
在官方文档里可以看到,- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode这个函数在iOS7里面已经deprecated了,取而代之的是boundingRectWithSize:options:attributes:context:这个函数。实际上这两个函数在iOS7里面的计算结果是一致的,都是带小数的。boundingRectWithSize:options:attributes:context:的文档中可以看到这么一句话:
This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.
也就是说,计算出的size需要用ceil函数取整。
在iOS7中,正确地计算UILabel可能占有的高度需要如下的步骤:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:someFont, NSParagraphStyleAttributeName:paragraphStyle.copy};
labelSize = [someText boundingRectWithSize:CGSizeMake(207, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
/*
This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.
*/
labelSize.height = ceil(labelSize.height);
labelSize.width = ceil(labelSize.width);
最新文章
- django学习记录--第一个网页“hello django”
- Activity的四种launchMode
- JQUERY 滚动 scroll事件老忘记 标记下
- XAML Region标签功能
- sqlite数据库 select 查询带换行符数据
- 探索 OpenStack 之(11):cinder-api Service 启动过程分析 以及 WSGI / Paste deploy / Router 等介绍
- 将文件读取到内存、打印pe结构
- Django中如何配置Database缓存?
- Cannot find class for bean with name service
- Android应用插件式开发解决方法[转]
- qq第3方登录的JS实现方式记录
- Oracle数据表被drop后的恢复
- mongodb生产环境(副本集模式)集群搭建配置
- Ubuntu 中登录相关的日志
- javaWeb学习之页面js树
- Linux:PCBSD系统的安装
- MFC编程之数值调节按钮
- nodejs之querystring(查询字符串)
- 100道Java基础面试题收集整理(附答案)
- Html5前端笔记
热门文章
- 【Linux】创建不可修改文件
- java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)
- Centos7.4下keepalived-1.3.5的安装使用
- DUBBO本地搭建及小案例 (转)
- 修改mysql数据引擎的方法- 提高数据库性能
- OSWorkFlow 学习
- 【laravel5.*】添加ide_helper.php 助手
- (转载)JWebUnit做Web项目自动化测试
- 简单的Java串口通讯应答示例
- mount 需要同时设置 noatime 和 nodiratime 吗?