错误的标签高度

时间:2015-01-21 10:32:40

标签: ios objective-c xcode ios8

我试图根据文本的长度来获取标签的高度。但如果单词不能放在一行中 - 单词的一部分转移到下一行。并且该方法仅返回一行的高度。任何人都可以帮助我吗?

- (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;

}

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;