Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel sizeThatFits not working

I'm trying to calculate the height for a UITableViewCell so I've defined a class method that looks like this

+ (CGFloat)heightWithText:(NSString *)text
{
    SizingLabel.text = text;
    [SizingLabel sizeThatFits:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)];

    return (TOP_MARGIN + SizingLabel.frame.size.height + BOTTOM_MARGIN);
}

I've defined SizingLabel like this:

+ (void)initialize
{
    SizingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    SizingLabel.numberOfLines = 0;
    SizingLabel.lineBreakMode = NSLineBreakByWordWrapping;
}

However, if i stick a breakpoint in the -heightWithText: method, i notice that the dimensions of SizingLabel never change and i thus get an incorrect value. Why is that?

like image 344
Sean Danzeiser Avatar asked Oct 28 '13 06:10

Sean Danzeiser


2 Answers

As said above, sizeThatFits: (and thus sizeToFit) do not work well with UILabel objects.

You better use the preferred textRectForBounds:limitedToNumberOfLines: method:

+ (CGFloat)heightWithText:(NSString *)text
{
    resizingLabel.text = text;
    CGSize labelSize = [resizingLabel textRectForBounds:CGRectMake(0.0, 0.0, LABEL_WIDTH, CGFLOAT_MAX)
                                 limitedToNumberOfLines:0].size; // No limit

    return (TOP_MARGIN + labelSize.height + BOTTOM_MARGIN);
}
like image 69
Rivera Avatar answered Oct 10 '22 04:10

Rivera


+ (CGFloat)heightWithText:(NSString *)text
{
    SizingLabel.text = text;
    CGSize labelSize = [SizingLabel sizeThatFits:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)];

    return (TOP_MARGIN + labelSize.height + BOTTOM_MARGIN);
}
like image 26
OnkarK Avatar answered Oct 10 '22 04:10

OnkarK