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

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

    If you are using auto-layout, you can use the following UITextView subclass that adds an intrinsic height:

    @implementation SelfSizingTextView
    
    - (void)setText:(NSString *)text
    {
        [super setText:text];
        [self invalidateIntrinsicContentSize];
    }
    
    - (void)setFont:(UIFont *)font
    {
        [super setFont:font];
        [self invalidateIntrinsicContentSize];
    }
    
    - (CGSize)intrinsicContentSize
    {
        CGFloat width = self.frame.size.width;
        CGSize size = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)];
        return CGSizeMake(UIViewNoIntrinsicMetric, size.height);
    }
    
    @end
    

提交回复
热议问题