6

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.

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
ArisRS
  • 1,362
  • 2
  • 19
  • 41

2 Answers2

11

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];
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Gypsa
  • 11,230
  • 6
  • 44
  • 82
  • modify the frame according to your requirement. – Gypsa May 20 '11 at 10:26
  • Hi, I've tried to set setNumberOfLines to 0. And it does't work us I understand your post? – ArisRS May 20 '11 at 11:05
  • 5
    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. – Gypsa May 20 '11 at 11:19
  • From iOS6 onwards `UILineBreakModeWordWrap` is deprecated. You can use `NSLineBreakByWordWrapping` – morksinaanab Jan 06 '14 at 07:16
  • You may need to set [label setPreferredMaxLayoutWidth:labelSize.Width] if you are dealing with auto layout. see this answer:http://stackoverflow.com/questions/12789013/ios-multi-line-uilabel-in-auto-layout I was using the Masonry library to generate auto layout constraints and this fixed it for me. – Lobsterman Aug 13 '15 at 20:10
2

Try before setText:

cell.exsInfoLabel.numberOfLines = 2;

Or:

cell.exsInfoLabel.numberOfLines = arrEx.count;
Roki
  • 2,680
  • 1
  • 22
  • 21