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?
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.
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
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