Eugene Trapeznikov
Eugene Trapeznikov

Reputation: 3240

Creating flexible 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?

Upvotes: 3

Views: 3371

Answers (3)

Julien
Julien

Reputation: 973

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.

Upvotes: 3

BBog
BBog

Reputation: 3650

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

Upvotes: 2

rob mayoff
rob mayoff

Reputation: 386038

You can set the label's numberOfLines property to specify how many lines it can wrap to. If you set it to zero, it can wrap to any number of lines. You can set this property in your nib.

However, you also need to set its frame large enough to show all of the lines. The easiest way is to send it the sizeToFit message after you set its text. It will keep its width (I think) but change its height to be tall enough to display all of its lines after wrapping.

If you might have so much text that it doesn't fit on the screen (or doesn't fit in the space available for your label), you should use a UITextView instead. A UITextView allows scrolling automatically.

Upvotes: 2

Related Questions