zoukankan      html  css  js  c++  java
  • iOS7.0中UILabel高度调整注意事项(转)

    注释:原文链接丢失。

    我的“记词助手”在升级到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);

  • 相关阅读:
    第07组 Beta冲刺 总结
    第07组 Beta冲刺 (5/5)
    第07组 Beta冲刺 (4/5)
    第07组 Beta冲刺 (3/5)
    第07组 Beta冲刺 (2/5)
    第07组 Beta冲刺 (1/5)
    软工实践个人总结
    第03组 Beta冲刺(5/5)
    第03组 Beta冲刺(4/5)
    第03组 Beta冲刺(3/5)
  • 原文地址:https://www.cnblogs.com/qiyer/p/5025565.html
Copyright © 2011-2022 走看看