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 newl开发者_如何学Cine '\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.
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.
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];
I couldn't get Scott & DoctorG's solution to work (though I didn't spend too much time trying), but here's the simple solution that works for me when I'm extracting escaped text from an xml file.
Inside my string function class, I define:
+(NSString)escapeXml:(NSString*)string {
return [string stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
}
精彩评论