iOS面试题:动态计算文本高度的时候需要注意什么?

96
iOS猿_员
0.2 2019.01.29 21:01* 字数 37

原文:iOS面试题大全

    + (CGSize)contentSizeForContent:(NSString *)content withFixedWidth:(CGFloat)width {
        CGSize maxSize = CGSizeMake(width, MAXFLOAT);
        UIFont *font = [UIFont systemFontOfSize:14.0];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment = NSTextAlignmentLeft;
        CGRect suggestRect = [content boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle} context:nil];
        
        CGSize resultSize = CGSizeMake(width, ceil(suggestRect.size.height));
        
        return resultSize;
    }

如上代码,需要注意算完高度需要用ceil来处理一下做向上取整。

iOS面试题小集
Web note ad 1