Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force UILabel to display 2 lines

I have UILabel that display single line if it have space for it.

However, I need to force it always display 2 lines, even if there is enough space for display it in 1 line.

Robust way is to reduce right spacing constraint and check that condition on all of available devices, but maybe there is an easier way?

To be clear, I want this:enter image description here

look like this: enter image description here

As I mentioned, now labels binded to superview by constraints.

like image 732
Evgeniy Kleban Avatar asked Jul 11 '16 13:07

Evgeniy Kleban


People also ask

How do you control line spacing in UILabel?

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels." This is a really old answer, and other have already addded the new and better way to handle this..

How do you add a new line on UILabel?

In Interface Builder's Label attributes, set # Lines = 0. Select the label and then change Lines property to 0 like in the above image, and then use \n in your string for line break. If you read a string from an XML file, the line break \n in this string will not work in UILabel text.

How do I change my UILabel text?

Changing the text of an existing UILabel can be done by accessing and modifying the text property of the UILabel . This can be done directly using String literals or indirectly using variables.


2 Answers

Step 1. Set number of lines to your label to 2.
Step 2. Set "Vertical hugging priority" to High (1000)
Step 3. Right click on your label and connect with icon at left and choose "Center Vertically".
Step 4. Right click on your label and connect with icon at left and set "Horizontal Spacing".
Step 5. If that text is static then do as suggested Igor, else, just replace @" " with @"\n" after assigning text to that label. E.g.

NSString *text = @"Какой-то Справочник"; 
self.myLabel.text = [text stringByReplacingOccurrencesOfString:@" " withString:@"\n"];

Or just set self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;

like image 74
arturdev Avatar answered Nov 15 '22 06:11

arturdev


In InterfaceBuilder settings of UILabel text press option+enter between "Справочник" and "МКБ".

Or set label.text = @"Справочник\nМКБ";.

And, of course, set yourLabel.numberOfLines = 2 or 0 in IB or code.

like image 20
Igor Avatar answered Nov 15 '22 08:11

Igor