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

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

    In iOS 8 you'll in inherit some content offset from the parent, which you need to get rid of as well.

    A subclass example

    // Originally from https://github.com/Nikita2k/resizableTextView
    
    #import "ResizableTextView.h"
    
    @implementation ResizableTextView
    
    - (void) updateConstraints {
    
        // calculate contentSize manually
        // ios7 doesn't calculate it before viewDidAppear and we'll get here before
        CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];
    
        // set the height constraint to change textView height
        [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
            if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                constraint.constant = contentSize.height;
                *stop = YES;
            }
        }];
    
        [super updateConstraints];
    }
    
    - (void)setContentOffset:(CGPoint)contentOffset
    {
        // In iOS 8 we seem to be inheriting the content offset from the parent.
        // I'm not interested
    }
    
    @end
    

提交回复
热议问题