How do I size a UITextView to its content on iOS 7?

前端 未结 13 1819
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 03:04

I\'ve been using the accepted answer here for years.

On iOS 7, the contentSize.height becomes the frame.height-8, regardless of text content.

What\'s a worki

13条回答
  •  北海茫月
    2020-11-28 03:40

    I use an adapted version of madmik's answer that eliminates the fudge factor:

    - (CGFloat)measureHeightOfUITextView:(UITextView *)textView
    {
        if ([textView respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])
        {
            // This is the code for iOS 7. contentSize no longer returns the correct value, so
            // we have to calculate it.
            //
            // This is partly borrowed from HPGrowingTextView, but I've replaced the
            // magic fudge factors with the calculated values (having worked out where
            // they came from)
    
            CGRect frame = textView.bounds;
    
            // Take account of the padding added around the text.
    
            UIEdgeInsets textContainerInsets = textView.textContainerInset;
            UIEdgeInsets contentInsets = textView.contentInset;
    
            CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
            CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
    
            frame.size.width -= leftRightPadding;
            frame.size.height -= topBottomPadding;
    
            NSString *textToMeasure = textView.text;
            if ([textToMeasure hasSuffix:@"\n"])
            {
                textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
            }
    
            // NSString class method: boundingRectWithSize:options:attributes:context is
            // available only on ios7.0 sdk.
    
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
    
            NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
    
            CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:attributes
                                                      context:nil];
    
            CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
            return measuredHeight;
        }
        else
        {
            return textView.contentSize.height;
        }
    }
    

提交回复
热议问题