[iOS] Fit the content size of UILabel automatically

In general, we call the sizeToFit of UILabel to implement the fitting content size automatically. In some case, if we want to fit the attributed string content, we use the boundingRectWithSize. But, unfortunately, we will encounter a bug if we set the paragraph style for the attributed string that to result in the height of UILabel is smaller than the real content size.

If you have this issue, you could follow these code to solve it.

Reference to the post in the StackOverflow

Can’t seem to calculate correct line-height of NSAttributedString for a UILabel

Here is the code,

- (CGSize)rectForAttributedString:(NSAttributedString *)string withSize:(CGSize)theSize
{
    if (!string || CGSizeEqualToSize(theSize, CGSizeZero)) {
        return CGSizeZero;
    }

    // setup TextKit stack
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:theSize];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:string];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];

    // query for size
    CGRect rect = [layoutManager usedRectForTextContainer:textContainer];

    return CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));
}

發佈留言