How to truncate UITextView contents to fit a reduced size?

前端 未结 4 472
轻奢々
轻奢々 2021-02-06 07:05

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

4条回答
  •  温柔的废话
    2021-02-06 07:43

    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]];
    

提交回复
热议问题