Search code examples
iosobjective-cautolayoutuilabel

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.


Solution

  • 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;