Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does UILabel's sizeThatFits return its height?

I'm trying to implement the following thing in my app:

themeLabel = [[UILabel alloc] init];
themeLabel.backgroundColor = [UIColor redColor];
themeLabel.text = themeString;
[themeLabel sizeThatFits:CGSizeMake(274, 274)];
themeLabel.numberOfLines = 0;
[topThemeView addSubview:themeLabel];

NSLog(@"Height is %f ", themeLabel.frame.size.height);

[themeLabel setFrame:CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 274, themeLabel.frame.size.height)];

And I end up with the Label's height that is 0.0. Any ideas why?

like image 565
Sergey Grischyov Avatar asked Feb 25 '13 14:02

Sergey Grischyov


3 Answers

themeLabel = [[UILabel alloc] init];
themeLabel.backgroundColor = [UIColor redColor];
themeLabel.text = themeString;
themeLabel.numberOfLines = 0;

CGRect labelFrame = CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 0.0, 0.0);
labelFrame.size = [themeLabel sizeThatFits:CGSizeMake(274, 274)];

[themeLabel setFrame:labelFrame];
[topThemeView addSubview:themeLabel];
like image 196
trojanfoe Avatar answered Oct 27 '22 02:10

trojanfoe


sizeThatFits asks the view to calculate and return the size that best fits its subviews. So you are never setting the frame of themeLabel

you should do:

themeLabel.numberOfLines = 0;
CGSize size = [themeLabel sizeThatFits:CGSizeMake(274, 274)];
themeLabel.frame = (CGRect) {0,0, size};
like image 41
peko Avatar answered Oct 27 '22 02:10

peko


I created a category for handling height for UILabels:

UILabel+TCFlexibleHeight.h:

#import <UIKit/UIKit.h>

@interface UILabel (TCFlexibleHeight)

- (CGFloat)heightForText:(NSString*)text;
- (CGFloat)heightForCurrentText;
- (CGFloat)adjustHeightForCurrentText;

@end

UILabel+TCFlexibleHeight.m:

#import "UILabel+TCFlexibleHeight.h"

static const NSInteger kMaxLines = 1000;

@implementation UILabel (TCFlexibleHeight)

- (CGFloat)heightForText:(NSString*)text {
    if (text == nil) {
        return 0;
    }

    NSInteger numberOfLines = self.numberOfLines > 0 ? self.numberOfLines : kMaxLines;
    CGSize size = CGSizeMake(self.frame.size.width, self.font.lineHeight * numberOfLines);
    return [text sizeWithFont:self.font constrainedToSize:size lineBreakMode:self.lineBreakMode].height;
}

- (CGFloat)heightForCurrentText {
    return [self heightForText:self.text];
}

- (CGFloat)adjustHeightForCurrentText {
    CGFloat height = [self heightForCurrentText];
    CGRect frame = self.frame;
    frame.size.height = height;
    return height;
}

@end

With this category your code will be something like this:

[themeLabel setFrame:CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 274, [themeLabel heightForCurrentText])];

Note that this category doesn't handle attributed strings and require the line wrapping set to clip to character.

like image 2
redent84 Avatar answered Oct 27 '22 01:10

redent84