How to add line break for UILabel?

后端 未结 21 2069
失恋的感觉
失恋的感觉 2020-11-29 14:53

Let see that I have a string look like this:

NSString *longStr = @\"AAAAA\\nBBBBB\\nCCCCC\";  

How do I make it so that the UILabel disp

相关标签:
21条回答
  • 2020-11-29 15:23

    It seems wrong to me to change the label frame sizes especially when using autolayout. Using the appendFormat method seems more appropriate. Here is my example:

    NSMutableString *list = [[NSMutableString alloc] init];
    NSArray *textArray = @[@"AAAA", @"BBBB"];
    for (NSString *string in textArray) {
        [list appendFormat:@"%@\n", string.mutableCopy];
    }
    self.label.text = list;
    self.label.numberOfLines = 0;
    
    0 讨论(0)
  • 2020-11-29 15:25

    For anyone else that might have trouble with sizeWithFont:constrainedToSize:lineBreakMode: or anyone switching to ios8 (the method is deprecated as of ios7), I adjusted my height by using sizeToFit instead.

    UILabel *label;
    label.numberOfLines = 0;
    // Setup label with desired settings
    ...
    [label sizeToFit];
    label.frame = CGRectMake(label.frame.origin.x,     // Or use any desired origin
                             label.frame.origin.y, 
                             label.frame.size.width,   // Or use any desired width
                             label.frame.size.height);
    
    0 讨论(0)
  • 2020-11-29 15:26

    // DO not forget to set numberOfLines to zero

    UILabel* locationTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 30, 230, 40)];
    locationTitle.font = [UIFont systemFontOfSize:13.0];
    locationTitle.numberOfLines = 0;
    locationTitle.text = [NSString stringWithFormat:@"Eaton industries pvt. Ltd \nUK Apr 12"];
    [cell addSubview:locationTitle];
    
    0 讨论(0)
  • 2020-11-29 15:27

    In my case also \n was not working, I fixed issue by keeping number of lines to 0 and copied and pasted the text with new line itself for example instead of Hello \n World i pasted

    Hello

    World

    in the interface builder.

    0 讨论(0)
  • 2020-11-29 15:28

    Use option-return when typing in the little box in Interface Builder to insert a line feed (\n). 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.

    0 讨论(0)
  • 2020-11-29 15:28

    If your using a UILabel you have to remember that the default setting is 1 line, so it does not matter how many breaks you add (\n or \r), you need to make sure it is set to more than one line so it could be allowed to append more lines.

    One alternative is to use UITextView which is really meant for multilines.

    You can easily achieve this in XCode attribute section of the UILabel, see screenshot:

    enter image description here

    0 讨论(0)
提交回复
热议问题