Instead of trying to find the length of the words and finding the size for the words, you can add a newline(\n
) character after the two words and display it in the label without altering the label's size or lineBreakMode.
- (NSString *)formatSentenceIntoTwoLines:(NSString *)sentence {
sentence = [sentence stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray *words = [sentence componentsSeparatedByString:@" "];
NSString *word_1 = [words objectAtIndex:0];
NSString *word_2 = [words objectAtIndex:1];
NSString *word_3 = [words objectAtIndex:2];
NSString *word_4 = [words objectAtIndex:3];
NSString *firstTwoWords = [word_1 stringByAppendingFormat:@" %@", word_2];
NSString *lastTwoWords = [word_3 stringByAppendingFormat:@" %@", word_4];
NSString *formattedSentence = [firstTwoWords stringByAppendingFormat:@"\n%@", lastTwoWords];
return formattedSentence;
}
Use the above method to format the string. The code seems too big. I write it in this way just to make it understandable. You can still simplify it as you want.
And make sure the numberOfLines of label set to 2
(label will show only two lines) or 0
(for dynamic number of lines).
label.numberOfLines = 2; // 0 if there is going to be dynamic number of lines