Here is my job for detecting line breaks inside UILabel
- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font { int length = 1; int lastSpace = 1; NSString *cutText = [str substringToIndex:length]; CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)]; while (textSize.height <= frame.size.height) { NSRange range = NSMakeRange (length, 1); if ([[str substringWithRange:range] isEqualToString:@" "]) { lastSpace = length; } length++; cutText = [str substringToIndex:length]; textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)]; } return lastSpace; } -(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point { //Create Label UILabel *label = [[UILabel alloc] init]; label.text = labelText; label.numberOfLines = 0; label.lineBreakMode = NSLineBreakByWordWrapping; //Set frame according to string CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; [label setFrame:CGRectMake(point.x , point.y , size.width , size.height)]; //Add Label in current view [self.view addSubview:label]; //Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode int numLines = (int)(label.frame.size.height/label.font.leading); //Getting and dumping lines from text set on the Label NSMutableArray *allLines = [[NSMutableArray alloc] init]; BOOL shouldLoop = YES; while (shouldLoop) { //Getting length of the string from rect with font int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1; [allLines addObject:[labelText substringToIndex:length]]; labelText = [labelText substringFromIndex:length]; if(labelText.length<length) shouldLoop = NO; } [allLines addObject:labelText]; //NSLog(@"\n\n%@\n",allLines); return [allLines componentsJoinedByString:@"\n"]; }
How to use
NSString *labelText = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far."; NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)]; NSLog(@"\n\n%@",stringWithLineBreakChar);
You just need to set the parameters needed by getLinebreaksWithString , and you will get a string with the word "\ n" included.
audio output 
Ξ²hargavαΈ―
source share