转自: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);

最新文章

  1. django学习记录--第一个网页“hello django”
  2. Activity的四种launchMode
  3. JQUERY 滚动 scroll事件老忘记 标记下
  4. XAML Region标签功能
  5. sqlite数据库 select 查询带换行符数据
  6. 探索 OpenStack 之(11):cinder-api Service 启动过程分析 以及 WSGI / Paste deploy / Router 等介绍
  7. 将文件读取到内存、打印pe结构
  8. Django中如何配置Database缓存?
  9. Cannot find class for bean with name service
  10. Android应用插件式开发解决方法[转]
  11. qq第3方登录的JS实现方式记录
  12. Oracle数据表被drop后的恢复
  13. mongodb生产环境(副本集模式)集群搭建配置
  14. Ubuntu 中登录相关的日志
  15. javaWeb学习之页面js树
  16. Linux:PCBSD系统的安装
  17. MFC编程之数值调节按钮
  18. nodejs之querystring(查询字符串)
  19. 100道Java基础面试题收集整理(附答案)
  20. Html5前端笔记

热门文章

  1. 【Linux】创建不可修改文件
  2. java中使用相对路径读取文件的写法总结 ,以及getResourceAsStream() (转)
  3. Centos7.4下keepalived-1.3.5的安装使用
  4. DUBBO本地搭建及小案例 (转)
  5. 修改mysql数据引擎的方法- 提高数据库性能
  6. OSWorkFlow 学习
  7. 【laravel5.*】添加ide_helper.php 助手
  8. (转载)JWebUnit做Web项目自动化测试
  9. 简单的Java串口通讯应答示例
  10. mount 需要同时设置 noatime 和 nodiratime 吗?