美文网首页iOS基础控件iOS 基础知识iOS 小册
iOS 获取 Label 高度的正确方式

iOS 获取 Label 高度的正确方式

作者: fuyoufang | 来源:发表于2016-11-28 16:34 被阅读3016次

    在设置 UILabelFrame 高度时,不能简单的设置为字体的 font size。否则会将字体的一部分裁剪掉。因为 UILabel 在不同的字体设置下,对 Frame 的高度要求也不一样,大多数情况下都比Font的高度设置要高一些。

    sizeThatFits

    使用 viewsizeThatFits 方法。

    // return 'best' size to fit given size. does not actually resize view. Default is return existing view size
    - (CGSize)sizeThatFits:(CGSize)size;     
    

    例子:

    UILabel *testLabel = [[UILabel alloc] init];
    testLabel.font = [UIFont systemFontOfSize:30];
    testLabel.text = @"Today is a fine day";
    CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
    NSLog(@"size = %@", NSStringFromCGSize(size));
    

    输出:size = {246.33333333333334, 36}

    sizeToFit

    使用 viewsizeToFit 方法。注意:sizeToFit 会改变 view 原来的 bounds,而 sizeThatFits 不会。

    // calls sizeThatFits: with current view bounds and changes bounds size.
    - (void)sizeToFit;                       
    

    例子

    UILabel *testLabel = [[UILabel alloc] init];
    testLabel.font = [UIFont systemFontOfSize:30];
    testLabel.text = @"Today is a fine day";
    [testLabel sizeToFit];
    NSLog(@"size = %@", NSStringFromCGSize(testLabel.frame.size));
    

    输出:size = {246.33333333333334, 36}

    sizeWithAttributes

    使用 NSStringsizeWithAttributes 方法。

    - (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs NS_AVAILABLE(10_0, 7_0);
    

    例子

    NSString *text = @"Today is a fine day";
    UIFont *font = [UIFont systemFontOfSize:30];
    CGSize size = [text sizeWithAttributes:@{
                                             NSFontAttributeName : font
                                             }];
    NSLog(@"size = %@", NSStringFromCGSize(size));
    

    输出: size = {246.3134765625, 35.80078125}

    boundingRectWithSize

    使用 NSStringboundingRectWithSize 方法。

    // NOTE: All of the following methods will default to drawing on a baseline, limiting drawing to a single line.
    // To correctly draw and size multi-line text, pass NSStringDrawingUsesLineFragmentOrigin in the options parameter.
    - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
    

    参数的意义:

    1. size
      限制最大宽高, 虽然是自适应,但是需要限制最大的宽度和高度。
    • options
      类型为 NSStringDrawingOptions,用来指明绘制字符串时的渲染选项。各个选项如下:

    typedef NS_OPTIONS(NSInteger, NSStringDrawingOptions) {
    // The specified origin is the line fragment origin, not the base line origin
    // 整个文本将以每行组成的矩形为单位计算整个文本的尺寸
    NSStringDrawingUsesLineFragmentOrigin = 1 << 0,

    // Uses the font leading for calculating line heights
    // 使用字体的行间距来计算文本占用的范围,即每一行的底部到下一行的底部的距离计算
    NSStringDrawingUsesFontLeading = 1 << 1, 
    
    // Uses image glyph bounds instead of typographic bounds
    // 将文字以图像符号计算文本占用范围,而不是排版的边界
    NSStringDrawingUsesDeviceMetrics = 1 << 3,
    
    // Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified.
    // Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.
    // 如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。
    // 如果 NSStringDrawingUsesLineFragmentOrigin 没有设置,则该选项不生效
    NSStringDrawingTruncatesLastVisibleLine NS_ENUM_AVAILABLE(10_5, 6_0) = 1 << 5, 
    

    } NS_ENUM_AVAILABLE(10_0, 6_0);

    
    - attributes
    应用于字符串的文本属性。
    
    - context
    `NSStringDrawingContext` 类型,控制调整字间距和缩放的比例,用于文本绘制时使用。该参数传入 nil 即可。
    
    例子
    

    NSString *text = @"Today is a fine day";
    UIFont *font = [UIFont systemFontOfSize:30];
    CGRect suggestedRect = [text boundingRectWithSize:CGSizeMake(800, MAXFLOAT)
    options:NSStringDrawingUsesFontLeading
    attributes:@{ NSFontAttributeName : font }
    context:nil];
    NSLog(@"size = %@", NSStringFromCGSize(suggestedRect.size));

    输出: size = {200, 35.80078125}
    
    # 四种方式对比
    在设置字体为 30 的情况下,前两种使用 `view` 的方法返回 size = {246.33333333333334, 36},后两种使用 `NSString` 的方法返回 size = {246.3134765625, 35.80078125}。使用 `view` 方法比使用  `NSString` 方法的返回的值略大。
    > 我猜测其原因都是因为,文本渲染引擎在渲染一行文本的时候都需要在label的顶部和底部预留一小部分空间,应该是出于排版美观方面的考量。
    
    在显示不同的 font size 的字体时,获得的字符串高度比 font size 大的值是不同的。
    比如 `font size` 为 13 时,算出高度为 16,`font size` 为 20 时,算出高度为 24。
    
    > 所以平常设置 UILabel 高度的时候,也不能简单的在 font height 基础之上加随意值。
    
    # 参考
    [理解NSStringDrawingOptions每个选项的用法与意义](http://www.itdadao.com/articles/c15a197037p0.html)
    [UILabel中一个很多人都会踩的坑](http://mp.weixin.qq.com/s?__biz=MzI5MjEzNzA1MA==&mid=2650264215&idx=1&sn=bce53cc5b98eef3f839760a4b9b5002c&chksm=f40683a2c3710ab4af58fa5e39a053c5997c4780da3df0f5acca189b6f8fc15a5c7cc26076f1&scene=0#rd)

    相关文章

      网友评论

        本文标题:iOS 获取 Label 高度的正确方式

        本文链接:https://www.haomeiwen.com/subject/jllopttx.html