Multiline UILabel?

13,053

Solution 1

try this:

CGSize labelsize;
UILabel *commentsTextLabel = [[UILabel alloc] init];
[commentsTextLabel setNumberOfLines:0];
[commentsTextLabel setBackgroundColor:[UIColor clearColor]];
NSString *text = @"yourtextString";
[commentsTextLabel setFont:[UIFont fontWithName:@"Helvetica"size:14]];
labelsize = [text sizeWithFont:commentsTextLabel.font 
             constrainedToSize:CGSizeMake(268, 2000.0) 
                 lineBreakMode:UILineBreakModeWordWrap];
commentsTextLabel.frame = CGRectMake(10, 24, 268, labelsize.height);
[cell.contentView addSubview:commentsTextLabel];
[commentsTextLabel release];

Solution 2

Try before setText:

cell.exsInfoLabel.numberOfLines = 2;

Or:

cell.exsInfoLabel.numberOfLines = arrEx.count;
Share:
13,053
ArisRS
Author by

ArisRS

Updated on June 04, 2022

Comments

  • ArisRS
    ArisRS almost 2 years

    I need insert to UILabel multiline text. I do the following:

    NSMutableString * spName = [[NSMutableString alloc ]initWithString:@""];
    
    for (NSUInteger i=0; i<arrEx.count; ++i)
    {
        ExInfo * exInf = [arrEx objectAtIndex:i];
        [spName appendString:[MyObject getName:exInf.spNum]];
        [spName appendString:@" "];
        [spName appendString:exInf.totalTime];
        [spName appendString:@"\n"];        
    }
    
    CGSize size = [spName sizeWithFont:[UIFont systemFontOfSize:14] 
                     constrainedToSize:constraint
                         lineBreakMode:UILineBreakModeWordWrap];
    
    [cell.exsInfoLabel setFrame:CGRectMake(CELL_CONTENT_MARGIN, top, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), size.height)];
    [cell.exsInfoLabel setText:spName];
    [spName release];
    

    arrEx consists of two items, so it should be two strings. But the UITableViewCell contains only the first string. In IB I set count of lines to 0 for the UILabel cell.exsInfoLabel.

  • Gypsa
    Gypsa almost 13 years
    modify the frame according to your requirement.
  • ArisRS
    ArisRS almost 13 years
    Hi, I've tried to set setNumberOfLines to 0. And it does't work us I understand your post?
  • Gypsa
    Gypsa almost 13 years
    number of lines 0 means you can add infinite number of lines. apple documentation says that:-This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.
  • morksinaanab
    morksinaanab over 10 years
    From iOS6 onwards UILineBreakModeWordWrap is deprecated. You can use NSLineBreakByWordWrapping
  • Lobsterman
    Lobsterman over 8 years
    You may need to set [label setPreferredMaxLayoutWidth:labelSize.Width] if you are dealing with auto layout. see this answer:stackoverflow.com/questions/12789013/… I was using the Masonry library to generate auto layout constraints and this fixed it for me.