480

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?

Krunal
  • 77,632
  • 48
  • 245
  • 261
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168
  • check this Question http://stackoverflow.com/questions/2312899/how-to-add-line-break-for-uilabel – user1766342 Feb 13 '13 at 07:17
  • 5
    Note that `UILineBreakModeWordWrap` was deprecated in iOS 6. You should now use `NSLineBreakByWordWrapping = 0` See the documentation [here](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/Reference/Reference.html#//apple_ref/c/tdef/NSLineBreakMode) – Austin Oct 03 '12 at 01:03

26 Answers26

850

Set the line break mode to word-wrapping and the number of lines to 0:

// Swift
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168
  • 20
    UILineBreakModeWordWrap is actually the default so you don't need the first line. – Jarred Olson Jul 30 '12 at 18:23
  • 1
    For those using swift: `cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping` and `cell.textLabel?.numberOfLines = 0` – boidkan Oct 21 '14 at 19:53
  • 6
    Thanks for also providing Xamarin-Code. Autocompletion didn't work because they chose to abbreviate that property... +1 – Jan Gillich Jan 13 '15 at 14:01
  • 1
    @JarredOlson Docs say " This property is set to byTruncatingTail by default." – Bill May 27 '17 at 23:00
  • I agree with Jarred Olson, **NSLineBreakByWordWrapping** is *default*. I added property **sizeToFit** like the guide of Gurumoorthy Arumugam to fix it. If you want the font inside your label to adjust itself to fit into the boundaries of the label. You can use : textLabel.adjustsFontSizeToFitWidth = YES; Thanks all. – ryan tran Feb 01 '15 at 04:40
  • It does not work. I can see just one line. – Darius Miliauskas Dec 17 '21 at 13:39
149

In IB, set number of lines to 0 (allows unlimited lines)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
  • 1
    [As he knowingly digs up a more-than-one-year-old thread …] One thing I sometimes wish I could do in IB is enter text *without* embedded line breaks, set UILineBreakModeWordWrap and numberOfLines = 0, and then have the label auto-size the height automagically, all the while still designing in IB. I'm thinking of the case where the view is resized to landscape, where line breaks in the label might be problematic. Or ... I could be misusing IB! Perhaps having the labels auto-size within IB causes more problems than it solves? (Also, you can't invoke sizeToFit at this point anyway.) – Joe D'Andrea May 11 '10 at 20:38
  • 1
    The "0" thing I got from the docs for UILabel, the alt-return from a friend who has been using Interface Builder for many years. – Kendall Helmstetter Gelner Sep 16 '11 at 23:37
  • 3
    +1 for being the only answer to mention "alt-return". In particular "ctrl-return" seems like it's going to work but does not. – paulmelnikow Mar 01 '13 at 20:51
  • Translation for Mac users: "alt-return" is equivalent to "option-return" – dorianDevTech Feb 25 '23 at 15:30
57

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

Just set number of lines to 0 in either IB or code

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;
Tieme
  • 62,602
  • 20
  • 102
  • 156
38

Use this to have multiple lines of text in UILabel:

textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

Swift:

textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
Taiwosam
  • 469
  • 7
  • 13
Abi
  • 501
  • 4
  • 6
24
myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];
Gurumoorthy Arumugam
  • 2,129
  • 1
  • 25
  • 40
19

If you have to use the:

myLabel.numberOfLines = 0;

property you can also use a standard line break ("\n"), in code, to force a new line.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
16

You can use \r to go to next line while filling up the UILabel using NSString.

UILabel * label;


label.text = [NSString stringWithFormat:@"%@ \r %@",@"first line",@"seconcd line"];
prajul
  • 1,216
  • 2
  • 15
  • 27
16

lets try this

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          
lal
  • 7,410
  • 7
  • 34
  • 45
user40910
  • 700
  • 1
  • 6
  • 17
13
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

The solution above does't work in my case. I'm doing like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // ...

    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
    return size.height + 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        // ...
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
    }

    // ...

    UILabel *textLabel = [cell textLabel];
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
                                        constrainedToSize:CGSizeMake(240.0, 480.0)
                                            lineBreakMode:UILineBreakModeWordWrap];

    cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);

    //...
}
bartolo-otrit
  • 2,396
  • 3
  • 32
  • 50
12

Swift 3
Set number of lines zero for dynamic text information, it will be useful for varying text.

var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

enter image description here

Krunal
  • 77,632
  • 48
  • 245
  • 261
8

Use story borad : select the label to set number of lines to zero......Or Refer this

enter image description here

Community
  • 1
  • 1
Vijay Sharma
  • 1,046
  • 9
  • 19
7

Try using this:

lblName.numberOfLines = 0;
[lblName sizeToFit];
Pang
  • 9,564
  • 146
  • 81
  • 122
Mubin Shaikh
  • 374
  • 4
  • 9
6
UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

For some reasons its not working for me in iOS 6 not sure why. Tried it with and without attributed text. Any suggestions.

Adrian P
  • 6,479
  • 4
  • 38
  • 55
Rajashekar
  • 619
  • 9
  • 30
6

Method 1:

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

Now call simply like this

myLbl.lblFunction()//Replace your label name 

EX:

Import UIKit

class MyClassName: UIViewController {//For example this is your class. 

    override func viewDidLoad() {
    super.viewDidLoad()

        myLbl.lblFunction()//Replace your label name 

    }

}//After close of your class write this extension.

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

Method 2:

Programmatically

yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping

Method 3:

Through Story board

To display multiple lines set 0(Zero), this will display more than one line in your label.

If you want to display n lines, set n.

See below screen.

enter image description here

If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option

See below screens

enter image description here

Here set minimum font size

EX: 9 (In this image)

If your label get more text at that time your label text will be shrink upto 9

enter image description here

Naresh
  • 16,698
  • 6
  • 112
  • 113
3

These things helped me

Change these properties of UILabel

label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;

And while giving input String use \n to display different words in different lines.

Example :

 NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;
iPhoneDeveloper
  • 958
  • 1
  • 14
  • 23
3

Swift 4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Sumona Salma
  • 127
  • 2
  • 14
2
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];
Gaurav Gilani
  • 1,584
  • 14
  • 18
2

You can do that via the Storyboard too:

  1. Select the Label on the view controller
  2. In the Attribute Inspector, increase the value of the Line option (Press Alt+Cmd+4 to show Attributes Inspector)
  3. Double click the Label in the view controller and write or paste your text
  4. Resize the Label and/or increase the font size so that the whole text could be shown
OsLivon
  • 49
  • 3
  • and set Lines to 0, otherwise it will only show text that can be put into the number of lines specified, others will be omitted. – toing_toing Mar 31 '16 at 04:33
2

you should try this:

-(CGFloat)dynamicLblHeight:(UILabel *)lbl
{
    CGFloat lblWidth = lbl.frame.size.width;
    CGRect lblTextSize = [lbl.text boundingRectWithSize:CGSizeMake(lblWidth, MAXFLOAT)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{NSFontAttributeName:lbl.font}
                                               context:nil];
    return lblTextSize.size.height;
}
Pritesh
  • 980
  • 7
  • 17
2

Oh, in 2021 I'm trapped by a label text unable to change lines for 1 hour, then realize I forget to set label's width, WTF.

let stepLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.lineBreakMode = .byWordWrapping
    label.numberOfLines = 0
    label.text = "Put your device and computer under same Wi-Fi network."
    
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    view.addSubview(stepLabel)

    NSLayoutConstraint.activate([
        stepLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        stepLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        stepLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7)
    ])
}
Zhou Haibo
  • 1,681
  • 1
  • 12
  • 32
1
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
Gaurav Gilani
  • 1,584
  • 14
  • 18
1

Already answered, but you can do it manually in the storyboard too. Under Attributes Inspector for the Label, you can change Line Breaks to Word Wrap (or character wrap).

Fleija
  • 290
  • 5
  • 10
1

In this function pass string that you want to assign in label and pass font size in place of self.activityFont and pass label width in place of 235, now you get label height according to your string. it will work fine.

-(float)calculateLabelStringHeight:(NSString *)answer
{
    CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
    return textRect.size.height;

}
McDowell
  • 107,573
  • 31
  • 204
  • 267
1

Set below either in code or in storyboard itself

Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;

and please don't forget to set left, right, top and bottom constraints for label otherwise it won't work.

garg
  • 2,651
  • 1
  • 24
  • 21
  • 1
    Everywhere it says to set word wrap and no.of lines to 0. But still mine did not wrap. Setting left, top, bottom & right constraint made it wrap. – anoo_radha Apr 05 '18 at 11:40
0

On C#, this worked for me inside UITableViewCell.

        UILabel myLabel = new UILabel();
        myLabel.Font = UIFont.SystemFontOfSize(16);
        myLabel.Lines = 0;
        myLabel.TextAlignment = UITextAlignment.Left;
        myLabel.LineBreakMode = UILineBreakMode.WordWrap;
        myLabel.MinimumScaleFactor = 1;
        myLabel.AdjustsFontSizeToFitWidth = true;

       myLabel.InvalidateIntrinsicContentSize();
       myLabel.Frame = new CoreGraphics.CGRect(20, mycell.ContentView.Frame.Y + 20, cell.ContentView.Frame.Size.Width - 40, mycell.ContentView.Frame.Size.Height);
       myCell.ContentView.AddSubview(myLabel);

I think the point here is:-

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;
Alvin George
  • 14,148
  • 92
  • 64
-2

This code is returning size height according to text

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}
Majid Bashir
  • 558
  • 1
  • 4
  • 27
Gaurav
  • 553
  • 5
  • 9