UITextView NSTextContainer wrong position at text view height NSLayoutConstraint change

I have subclassed UITextView

so that it returns the content's own size, for example:

- (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 added an observer to UITextViewTextDidChangeNotification

, and when the content of the text view changes, I update its height to increase 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 there are enough lines of them to fill the height of the text view, half the time when a new line is added, the NSTextContainer UITextView is not placed like you can see in this picture

enter image description here

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

I have not found how to solve this strange behavior.
Hopefully one of you has an answer to fix this.

thank

+3


source to share





All Articles