我已经将UITextView
子类化,使其返回如下内在大小:
- (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;
}
我已向UITextViewTextDidChangeNotification
添加了一个观察者,当文本视图内容发生变化时,我会更新其高度以使其以文本高度增长:
- (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];
}
但是当它们足够的线条来填充文本视图高度时,添加新行的一半时间UITextView的NSTextContainer放置不正确就像你在这张图片中看到的那样
(NSTextContainer用红色标出,UITextView用蓝色标出)
添加新行的另一半时间NSTextContainer被正确替换。
我没有找到如何解决这种奇怪的行为 我希望你们中的一个人能有一个解决方法。
谢谢