gsempe
gsempe

Reputation: 5499

UITextView's NSTextContainer wrong position on text view height NSLayoutConstraint change

I have subclassed UITextView to make it return an intrinsic content size like this:

- (void) layoutSubviews
{
    [super layoutSubviews];

    if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
        [self invalidateIntrinsicContentSize];
    }
}

- (CGSize)intrinsicContentSize
{
    /*
     Intrinsic content size of a textview is UIViewNoIntrinsicMetric
     We have to build what we want here: contentSize + textContainerInset should do the trick
     */
    CGSize intrinsicContentSize = self.contentSize;

    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;
}

I have added an observer to the UITextViewTextDidChangeNotification and when the text view content change I update its height to make it growth with the text height:

- (void)textViewTextDidChangeNotification:(NSNotification *)notification
{
    UITextView *textView = (UITextView *)notification.object;

    [self.view layoutIfNeeded];
    void (^animationBlock)() = ^
    {
        self.messageInputViewHeightConstraint.constant = MAX(0, self.messageInputView.intrinsicContentSize.height);
        [self.view layoutIfNeeded];
    };

    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:animationBlock
                     completion:nil];
}

But when their is enough lines to fill the text view height, half of the time when a new line is added the NSTextContainer of the UITextView is not well placed like you can see in this picture

enter image description here

(The NSTextContainer is outlined in red and UITextView is outlined in blue)
The other half of the time when a new line is added the NSTextContainer is replaced correctly.

I did not found how to solve this weird behavior.
I hope one of you will have an answer to fix it.

Thank you

Upvotes: 3

Views: 772

Answers (0)

Related Questions