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?
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];
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};
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.
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