I recently needed to split an NSString to fit in a certain width. Though you can accomplish this with a UILabel with line breaks set to word wrap and number of lines set to zero or more than one, I needed to display a very particular spacing between the two lines. Unfortunately UILabel gives no control over this so I used two carefully placed UILabels to display the text. I hope Apple will add control over multi line UILabel line height in the future.
Anyway, I ended up writing a method that takes the string to be split and the maximum character count and returns an array consisting of the separated strings. Here it is:
- (NSArray *)splitString:(NSString*)str maxCharacters:(NSInteger)maxLength {
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
NSArray *wordArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSInteger numberOfWords = [wordArray count];
NSInteger index = 0;
NSInteger lengthOfNextWord = 0;
while (index < numberOfWords) {
NSMutableString *line = [NSMutableString stringWithCapacity:1];
while ((([line length] + lengthOfNextWord + 1) <= maxLength) && (index < numberOfWords)) {
lengthOfNextWord = [[wordArray objectAtIndex:index] length];
[line appendString:[wordArray objectAtIndex:index]];
index++;
if (index < numberOfWords) {
[line appendString:@" "];
}
}
[tempArray addObject:line];
}
return tempArray;
}











hello i need to display an NSString which i created from a NSMutableArray, to fit the width of the UItextView
thanks, it helped me a little, UI Label is pretty lame,
I think the length of the next word should be
lengthOfNextWord = [[wordArray objectAtIndex:index+1] length];