How to truncate UITextView contents to fit a reduced size?

前端 未结 4 407
轻奢々
轻奢々 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:44

    Because sizeWithFont:constrainedToSize:lineBreakMode: is deprecated in iOS 7, I made a few changes:

    - (NSString *)stringByDeletingWordsFromStringToFit:(CGRect)rect
                                         withInset:(CGFloat)inset
                                         usingFont:(UIFont *)font
    {
        NSString *result = [self copy];
        CGSize maxSize = CGSizeMake(rect.size.width  - (inset * 2), FLT_MAX);
        if (!font) font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        CGRect boundingRect = [result boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font, } context:nil];
        CGSize size = boundingRect.size;
        NSRange range;
    
        if (rect.size.height < size.height)
            while (rect.size.height < size.height) {
    
                range = [result rangeOfString:@" "
                                        options:NSBackwardsSearch];
    
                if (range.location != NSNotFound && range.location > 0 ) {
                    result = [result substringToIndex:range.location];
                } else {
                    result = [result substringToIndex:result.length - 1];
                }
    
                if (!font) font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
                CGRect boundingRect = [result boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font, } context:nil];
                size = boundingRect.size;
            }
    
        return result;
    

    }

提交回复
热议问题