Last Updated: May 25, 2016
·
1.489K
· krzyzanowskim

Height of UILabel

The only realiable way to calculate height of the string is this one. Use it or soon you'll find out that for some combination of string/font/width you label is not high enough.

There is solution, everything else will fail (yes, all UIKIt methods, and CTFramesetterSuggestFrameSizeWithConstraints will fail as well)

+ (CGFloat)heightForAttributedString:(NSAttributedString *)attrString forWidth:(CGFloat)inWidth
{
    CGFloat H = 0;

    // Create the framesetter with the attributed string.
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString( (CFMutableAttributedStringRef) attrString);

    CGRect box = CGRectMake(0,0, inWidth, CGFLOAT_MAX);

    CFIndex startIndex = 0;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, box);

    // Create a frame for this column and draw it.
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(startIndex, 0), path, NULL);

    // Start the next frame at the first character not visible in this frame.
    //CFRange frameRange = CTFrameGetVisibleStringRange(frame);
    //startIndex += frameRange.length;

    CFArrayRef lineArray = CTFrameGetLines(frame);
    CFIndex j = 0, lineCount = CFArrayGetCount(lineArray);
    CGFloat h, ascent, descent, leading;

    for (j=0; j < lineCount; j++)
    {
        CTLineRef currentLine = (CTLineRef)CFArrayGetValueAtIndex(lineArray, j);
        CTLineGetTypographicBounds(currentLine, &ascent, &descent, &leading);
        h = ascent + descent + leading;
        H+=h;
    }

    CFRelease(frame);
    CFRelease(path);
    CFRelease(framesetter);

    return H;
}

1 Response
Add your response

This only work with AutoLayout off. With auto layout you its more easy,,, https://medium.com/ios-os-x-development/3e50cd1d1278

Thanks!

over 1 year ago ·