How to truncate UITextView contents to fit a reduced size?

前端 未结 4 420
轻奢々
轻奢々 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 08:03

    Original Answer (iOS 6 and below)

    Sadly, UILabel with numberOfLines wont do it if you need the view to be editable. Or you want UITextView's (native) vertical alignment.

    Here's an NSString category that deletes words from a string, according to it's size in a rect:

    @interface NSString (StringThatFits)
    - (NSString *)stringByDeletingWordsFromStringToFit:(CGRect)rect
                                             withInset:(CGFloat)inset
                                             usingFont:(UIFont *)font
    @end
    
    @implementation NSString (StringThatFits)
    - (NSString *)stringByDeletingWordsFromStringToFit:(CGRect)rect
                                             withInset:(CGFloat)inset
                                             usingFont:(UIFont *)font
    {
        NSString *result = [self copy];
        CGSize maxSize = CGSizeMake(rect.size.width  - (inset * 2), FLT_MAX);
        CGSize size = [result sizeWithFont:font
                               constrainedToSize:maxSize
                                   lineBreakMode:UILineBreakModeWordWrap];
        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];
                }
    
                size = [result sizeWithFont:font
                                constrainedToSize:maxSize
                                    lineBreakMode:UILineBreakModeWordWrap];
            }
    
        return result;
    }
    @end
    

    For a UITextView, use an inset of 8 to account for the way UIKit draws them:

    CGRect rect = aTextView.frame;
    NSString *truncatedString = [theString stringByDeletingWordsFromStringToFit:rect
                                         withInset:8.f
                                         usingFont:theTextView.font];
    

    Updated Answer (iOS 7)

    Now UITextView uses TextKit internally, it's much easier.

    Rather than truncating the actual string, set the text (or attributedText) property to the whole string and truncate the amount of text displayed in the container (just like we do with UILabel):

    self.textView.scrollEnabled = NO;
    self.textView.textContainer.maximumNumberOfLines = 0;
    self.textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
    

提交回复
热议问题