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

前端 未结 13 1818
伪装坚强ぢ
伪装坚强ぢ 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:42

    this method seems to work.

    // Code from apple developer forum - @Steve Krulewitz, @Mark Marszal, @Eric Silverberg
    - (CGFloat)measureHeight
    {
    if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])
    {
        CGRect frame = internalTextView.bounds;
        CGSize fudgeFactor;
        // The padding added around the text on iOS6 and iOS7 is different.
        fudgeFactor = CGSizeMake(10.0, 16.0);
    
        frame.size.height -= fudgeFactor.height;
        frame.size.width -= fudgeFactor.width;
    
        NSMutableAttributedString* textToMeasure;
        if(internalTextView.attributedText && internalTextView.attributedText.length > 0){
            textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];
        }
        else{
            textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];
            [textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];
        }
    
        if ([textToMeasure.string hasSuffix:@"\n"])
        {
            [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@"-" attributes:@{NSFontAttributeName: internalTextView.font}]];
        }
    
        // NSAttributedString class method: boundingRectWithSize:options:context is
        // available only on ios7.0 sdk.
        CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                                  context:nil];
    
        return CGRectGetHeight(size) + fudgeFactor.height;
    }
    else
    {
        return self.internalTextView.contentSize.height;
    }
    }
    

提交回复
热议问题