Skip to content

Instantly share code, notes, and snippets.

@wokalski
Created July 13, 2012 10:27
Show Gist options
  • Save wokalski/3104114 to your computer and use it in GitHub Desktop.
Save wokalski/3104114 to your computer and use it in GitHub Desktop.
Divide long string into pieces to fit a width . -(void) divideLongString:(NSString *) string toFitWidth:(CGFloat) width withFont: (UIFont *) font
-(NSMutableArray*) divideLongString:(NSString *) string toFitWidth:(CGFloat) width withFont: (UIFont *) font {
NSMutableArray* retArray = [NSMutableArray array];
CGSize stringSize = [string sizeWithFont:font];
float ratio = width/stringSize.width;
int difference = (int) stringSize.width % (int) width;
int numberOfLines = (stringSize.width - difference) /width;
NSRange range;
range.location = 0;
int charsReturned = 0;
int numberOfChars = abs(ratio * string.length);
range.length = numberOfChars;
for (int i = 0; i<numberOfLines; i++) {
[retArray addObject:[string substringWithRange:range]];
charsReturned += numberOfChars;
range.location += numberOfChars;
}
if (charsReturned < string.length) {
[retArray addObject:[string substringFromIndex:range.location]];
}
return retArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment