I've got an UILabel in a Detail View Controller, so its content changes depending on the selected table row. I have a problem, I would set a fixed width for my UILabel and a dynamic height depending on the text. How can I do this? (I'm sorry for my mistakes, but I'm not English)
A view that displays one or more lines of informational text.
To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.
To summarize, you can calculate the height of a label by using its string and calling boundingRectWithSize . You must provide the font as an attribute, and include . usesLineFragmentOrigin for multi-line labels.
I like to subclass UILabel
to do this for me.
AutosizingLabel.h
#import <UIKit/UIKit.h>
@interface AutosizingLabel : UILabel {
double minHeight;
}
@property (nonatomic) double minHeight;
- (void)calculateSize;
@end
AutosizingLabel.m
#define MIN_HEIGHT 10.0f
#import "AutosizingLabel.h"
@implementation AutosizingLabel
@synthesize minHeight;
- (id)init {
if ([super init]) {
self.minHeight = MIN_HEIGHT;
}
return self;
}
- (void)calculateSize {
CGSize constraint = CGSizeMake(self.frame.size.width, 20000.0f);
CGSize size = [self.text sizeWithFont:self.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[self setLineBreakMode:UILineBreakModeWordWrap];
[self setAdjustsFontSizeToFitWidth:NO];
[self setNumberOfLines:0];
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, MAX(size.height, MIN_HEIGHT))];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self calculateSize];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self calculateSize];
}
@end
To use this, import/create the .h and .m files in your project. Then if you are creating your UILabel
in code, it would look something like this:
#import "AutosizingLabel.h"
- (void)viewDidLoad {
[super viewDidLoad];
AutosizingLabel *label = [[AutosizingLabel alloc] init];
label.text = @"Some text here";
[self.view addSubview:label];
}
If you're using a XIB, you can select any UILabel and click on the Identity Inspector in the right sidebar to set it's class to AutosizingLabel
. In either case, setting the .text
property will auto update the size of the label.
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