Search This Blog

Saturday, September 18, 2010

Compute needed height for fixed width of NSAttributedString



this function can helps us to determines the frame sizeneeded for a string range of an NSAttributedString in iphone/Ipad SDK for a given Width :

 it can be used for a dynamic height of UITableView Cells


- (CGSize)frameSizeForAttributedString:(NSAttributedString *)attributedString
{
    CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
    CGFloat width = YOUR_FIXED_WIDTH;
   
    CFIndex offset = 0, length;
    CGFloat y = 0;
    do {
        length = CTTypesetterSuggestLineBreak(typesetter, offset, width);
        CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(offset, length));
       
        CGFloat ascent, descent, leading;
        CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
       
        CFRelease(line);
       
        offset += length;
        y += ascent + descent + leading;
    } while (offset < [attributedString length]);
   
    CFRelease(typesetter);
   
    return CGSizeMake(width, ceil(y));
}

2 comments:

  1. Sadly this gives the same faulty results as NSAttributedString boundingRectWithSize. Thanks anyways though

    ReplyDelete