UITextView that expands to text using auto layout

前端 未结 16 2058
面向向阳花
面向向阳花 2020-11-28 01:25

I have a view that is laid out completely using auto layout programmatically. I have a UITextView in the middle of the view with items above and below it. Everything works f

16条回答
  •  一向
    一向 (楼主)
    2020-11-28 01:42

    UITextView doesn't provide an intrinsicContentSize, so you need to subclass it and provide one. To make it grow automatically, invalidate the intrinsicContentSize in layoutSubviews. If you use anything other than the default contentInset (which I do not recommend), you may need to adjust the intrinsicContentSize calculation.

    @interface AutoTextView : UITextView
    
    @end
    

    #import "AutoTextView.h"
    
    @implementation AutoTextView
    
    - (void) layoutSubviews
    {
        [super layoutSubviews];
    
        if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
            [self invalidateIntrinsicContentSize];
        }
    }
    
    - (CGSize)intrinsicContentSize
    {
        CGSize intrinsicContentSize = self.contentSize;
    
        // iOS 7.0+
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
            intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;
            intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;
        }
    
        return intrinsicContentSize;
    }
    
    @end
    

提交回复
热议问题