UILabel动态宽度计算多行

时间:2014-03-31 08:01:41

标签: ios iphone objective-c cocoa-touch uilabel

我有UILabel我有2行文字。我使用以下代码计算动态宽度高度

CGSize expectedLabelSize = [[aLabel text] sizeWithFont:aLabel.font
                                         constrainedToSize:aLabel.frame.size
                                             lineBreakMode:aLabel.lineBreakMode];

 CGRect rect =  [aLabel frame];
    rect.size.width = expectedLabelSize.width;
    [aLabel setFrame:rect];

现在,如果UILabel中有多行,我该如何检测宽度。查看图像以获得更多清晰度。 End Co-ordinates of UILabel text

1 个答案:

答案 0 :(得分:0)

为Label

设置属性
label.numberOfLines = 0;

CGFloat labelHeight=  [self heightOfLabelWithIngredientLine:pixers.name];

[label setFrame:CGRectMake(10,10,100,labelHeight)];

- (CGFloat)heightOfLabelWithIngredientLine:(NSString *)stringLabel
{

    CGRect frame;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica" size:14.0f], NSFontAttributeName, nil];
    frame = [stringLabel boundingRectWithSize:CGSizeMake(20.0f, 999.0f) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributesDictionary context:nil];
    return frame.size.height;
}

中自定义标签属性
- (CGFloat)heightOfLabelWithIngredientLine:(NSString *)stringLabel

方法