2013-06-27 81 views
1

我想用NSParagraphStyle屬性計算NSAttributedString的高度。使用NSParagraphStyle從NSAttributedString計算高度

我認爲這將是很容易創建一個UILabel之間線間距較大但我不能計算我的UITableViewCell正確的高度。

我試着用boundingRectWithSize:options:來計算它,但它不工作在所有...

+0

不是* size *屬性返回正確的值嗎? –

+0

不是大小正在返回一個redicilous寬度。 – mariusLAN

+1

您是否在屬性字典中設置了字體? –

回答

0

當蘋果的方便易方法不工作,這一類提供在大多數情況下獲得良好aproximation。

@implementation NSAttributedString (PixLib) 

- (CGFloat)heightForWidth:(CGFloat)width { 
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathAddRect(path, NULL, CGRectMake(0, 0, width, 99999)); 
    CGFloat h = [self heightForPath:path]; 
    CGPathRelease(path); 
    return h; 
} 

- (CGFloat)heightForPath:(CGPathRef)path { 
    CGFloat height = 0; 
    CTFrameRef frame = [self cfframeForPath:path]; 
    if (frame != NULL) { 
     NSArray* lines = (__bridge NSArray*)CTFrameGetLines(frame); 

     int l = [lines count]; 
     if (l > 1) { 
      CGPoint origins[l]; 

      CTFrameGetLineOrigins(frame, CFRangeMake(0, l), origins); 

      CGFloat yFirst = origins[0].y; 
      CGFloat yLast = origins[l-1].y; 

      CGFloat ascent, descent, leading; 
      CTLineGetTypographicBounds((__bridge CTLineRef)[lines objectAtIndex:l-1], &ascent, &descent, &leading); 

      height = ceilf((ascent+descent+leading)*1.3) + yFirst-yLast; 
     } else { 
      if (l==1) { 
       CGFloat ascent, descent, leading; 
       CTLineGetTypographicBounds((__bridge CTLineRef)[lines objectAtIndex:0], &ascent, &descent, &leading); 
       height = ceilf(ascent+descent+leading)*1.3; 
      } 
     } 
     CFRelease(frame); 
    } 
    return height; 
} 

- (CTFrameRef)cfframeForPath:(CGPathRef)p { 
    // hack to avoid bugs width different behavior in iOS <4.3 and >4.3 
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGRect r = CGPathGetBoundingBox(p); 

    CGAffineTransform t = CGAffineTransformIdentity; 

    t = CGAffineTransformTranslate(t, r.origin.x, r.origin.y); 
    t = CGAffineTransformScale(t, 1, -1); 
    t = CGAffineTransformTranslate(t, r.origin.x, - (r.origin.y + r.size.height)); 
    CGPathAddPath(path, &t, p); 

    CGPathMoveToPoint(path, NULL, 0, 0); 
    CGPathCloseSubpath(path); 
    // hack end 

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self); 
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); 

    CFRelease(framesetter); 
    CGPathRelease(path); 
    return frame; 
} 

@end 
+0

它不適用於行間距。我添加一個NSParagrahStyle到NSAttributedLabel,但它不計算行距... – mariusLAN