I\'m having real trouble getting my head around this issue.
As the title suggests, I have several UITextViews on a view in an iPhone application. I am programmatically c
Here's a peace of code i wrote to truncate a string (by words) to fit a certain width and height:
- (NSString *)stringByTruncatingString:(NSString *)string toHeight:(CGFloat)height maxWidth:(CGFloat)width withFont: (UIFont *)font {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
NSMutableString *truncatedString = [string mutableCopy];
if ([string sizeWithAttributes: @{NSFontAttributeName: font}].height > height) {
// this line is optional, i wrote for better performance in case the string is too big
if([truncatedString length] > 150) truncatedString = [[truncatedString substringToIndex:150] mutableCopy];
// keep removing the last word until string is short enough
while ([truncatedString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil].size.height > height) {
NSRange wordrange= [truncatedString rangeOfString: @" " options: NSBackwardsSearch];
truncatedString = [[truncatedString substringToIndex: wordrange.location] mutableCopy];
}
// add elipsis to the end
truncatedString = [NSMutableString stringWithFormat:@"%@...",truncatedString];
}
return truncatedString;
}
Usage:
NSString *smallString = [self stringByTruncatingString:veryBigString toHeight:65 maxWidth:200 withFont:[UIFont systemFontSize:14.0f]];