Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line breaks not working in UILabel

I'm loading some help text from a plist and displaying the same in the form of UILabels housed in a UIScrollView. Portion of the code follows:

    UILabel *sectionDetailLabel = [[[UILabel alloc] initWithFrame:CGRectMake(34, myOriginForThisSection, 286, 20)] autorelease];
    sectionDetailLabel.backgroundColor = [UIColor clearColor];
    sectionDetailLabel.numberOfLines = 0;
    sectionDetailLabel.font = [UIFont systemFontOfSize:12];
    sectionDetailLabel.textColor = [UIColor blackColor];
    sectionDetailLabel.textAlignment = UITextAlignmentLeft;
    sectionDetailLabel.lineBreakMode = UILineBreakModeWordWrap;

    [baseScrollView addSubview:sectionDetailLabel];

    [sectionDetailLabel setText:myStringForThisSection];
    [sectionDetailLabel sizeToFit];

While any 'long' text is getting wrapped into multiple lines correctly, I'm unable to manually insert any line-breaks using newline '\n' characters in 'myStringForThisSection'. I only see the characters '\' and 'n' printed in the UILabel wherever I wanted the line-break, instead.

I looked this up and the general consensus seemed to be that setting numberOfLines to 0, setting the lineBreakMode to a valid value and invoking sizeToFit (or setting the frame of the UILabel based on sizeWithFont:) should do. All of which I seem to be doing in the code above - and works perfectly when fitting long strings of unknown length into multiple lines on the UILabel. So what could be missing here?

Note: All the variables used - baseScrollView, myStringForThisSection and myOriginForThisSection - were loaded before the above code began executing, and work fine.

like image 527
Dev Kanchen Avatar asked Mar 31 '10 18:03

Dev Kanchen


2 Answers

UILabel doesn't interpret the escape sequence \n. You can insert the real character that represents the Carriage Return and/or the Line Feed. Make a char to hold your newline and then insert it.

unichar newLine = '\n';
NSString *singleCR = [NSString stringWithCharacters:&newLine length:1];
[myStringForThisSection insertString:singleCR atIndex:somePlaceIWantACR];

As long as your myStringForThisSection is mutable, that should do it.

like image 188
Scott Gustafson Avatar answered Oct 10 '22 02:10

Scott Gustafson


I had trouble with Scot Gustafson's answer above in XCode 4.3

Try this instead:

unichar chr[1] = {'\n'};
NSString *cR = [NSString stringWithCharacters:(const unichar *)chr length:1];

Then use in your code something like this:

self.myLabel.text = [NSString stringWithFormat:@"First Label Line%@Second Label Line", cR];
like image 32
DoctorG Avatar answered Oct 10 '22 03:10

DoctorG