zoukankan      html  css  js  c++  java
  • 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错位的问题:

    ios7label

    我的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);

  • 相关阅读:
    JS中数组的sort()排序
    清除浮动方法
    浏览器兼容问题
    前端切图
    设置页面默认为繁体字
    7月计划
    css的层叠和继承
    Flex 布局教程:语法篇
    轮播图淡入淡出的js和jquery的效果
    接口调用async/await
  • 原文地址:https://www.cnblogs.com/wangpei/p/4240027.html
Copyright © 2011-2022 走看看