Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating flexible UILabel

Tags:

xcode

ios

uilabel

I got an app with some text data.

From TableView user choose one cell and then see UIViewController with relative text data. But information text could be from 1 line to N. How can create such UILabel, which will change size depending on size of text?

like image 453
Eugene Trapeznikov Avatar asked Feb 24 '26 11:02

Eugene Trapeznikov


2 Answers

In the NSString UIKit Additions, you can find the following method:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

with this one you can define the optimal height or width of your label. For example, to get the optimal height of a UILabel, you can create a category on UILabel with the following method:

- (float)optimalHeight
{
    return [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(self.frame.size.width, UINTMAX_MAX) lineBreakMode:self.lineBreakMode].height;
}

after that, you can simply change the frame of your UILabel. Don't forget to set the number of line of your label to 0.

like image 179
Julien Avatar answered Feb 27 '26 01:02

Julien


Another solution would be to do this inside the code, with the sizeWithFont method. you can find more info here: iOS: UILabel dynamic height using sizeWithFont:constrainedToSize:lineBreakMode: not working

If it's the height that varies, you could set a maximum label size, with your standard label width and 9999 height, and then check what the suggested size would be for your text, using the font of your label

like image 35
BBog Avatar answered Feb 26 '26 23:02

BBog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!