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?
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);
}
+ (CGFloat)heightWithText:(NSString *)text
{
    SizingLabel.text = text;
    CGSize labelSize = [SizingLabel sizeThatFits:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)];
    return (TOP_MARGIN + labelSize.height + BOTTOM_MARGIN);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With