2015-01-21 113 views
0

我試圖根據文本的長度來獲取標籤的高度。但是,如果這個詞不能合併成一行,那麼這個詞的一部分就會轉移到下一行。該方法只返回一行的高度。誰能幫我 ?錯誤的標籤高度

- (CGFloat)heightFromText:(NSString *)text{ 
if (!text) { 
    return 0.0; 
} 
UIFont *font = [UIFont systemFontOfSize:16.0]; 
UIColor *color = [UIColor colorWithColorCode:@"438fbe"]; 
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle alloc]; 
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping; 
NSDictionary *attributes = @{NSForegroundColorAttributeName : color, NSFontAttributeName : font, NSParagraphStyleAttributeName : paragraphStyle}; 
NSAttributedString *attributed = [[NSAttributedString alloc] initWithString:text attributes:attributes]; 
CGRect needed = [attributed boundingRectWithSize:CGSizeMake(self.width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil]; 
CGFloat textHeight = ceilf(needed.size.height); 
return textHeight; 

}

回答

1

嘗試一個UILabel代替,像這樣:

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(x,y,w,h)]; 
lbl.font=font; 
lbl.numberOfLines=0; // will do as many lines as you need 
lbl.textAlignment=NSTextAlignmentLeft; 
lbl.attributedText=attString; 

CGSize size = [lbl.text sizeWithFont:lbl.font 
         constrainedToSize:CGSizeMake(lbl.frame.size.width, MAXFLOAT) 
          lineBreakMode:NSLineBreakByWordWrapping]; 
return size.height; 
+0

因此,當我創建標籤指定什麼高度? 0.0? – MacUser 2015-01-21 11:23:37

+0

沒關係 - 0應該沒問題 – dijipiji 2015-01-21 12:16:52

0

這項工作對我來說:

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"YOUR_FONT" size:FONT_SIZE], NSFontAttributeName, nil]; 

CGRect frame = [YOUR_TEXT boundingRectWithSize:CGSizeMake(MAX_FRAME_WIDTH, MAX_FRAME_HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDictionary context:nil]; 

CGSize size = frame.size;