我在顶部键盘上添加textView
进行快速回复。我正在执行以下操作来重新计算内部包含textView
的容器的高度。
这是我的代码:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSLog(@"inputView is %@",NSStringFromCGRect(self.inputView.frame));
CGSize constraint = CGSizeMake(self.inputView.frame.size.width, self.inputView.frame.size.height);
NSDictionary *stringAttributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:self.inputView.font.pointSize] };
CGSize textSize = [self.inputView.text boundingRectWithSize:constraint
options:NSStringDrawingUsesFontLeading
attributes:stringAttributes
context:nil].size;
[UIView animateWithDuration:.2
animations:^{
CGRect r = self.frame;
r.origin.y -= ceil(textSize.height); // use ceil function to avoid we have a gap between textview and kboard during transition
r.size.height += ceil(textSize.height);
self.frame = r;
}
completion:^(BOOL finished) {
NSLog(@"frame is %@",NSStringFromCGRect(self.frame));
}
];
return YES;
}
然而,问题在于textView
保持增长如下
有什么方法可以避免这种情况吗?当 text 进入第二行或点击返回时,我只希望textView
增长。
答案 0 :(得分:0)
请尝试以下代码:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
[UIView animateWithDuration:.2
animations:^{
CGRect frame = self.myTextView.frame;
if (self.myTextView.contentSize.height > frame.size.height) {
CGFloat offset = self.myTextView.contentSize.height - frame.size.height;
frame.size.height = self.myTextView.contentSize.height;
frame.origin.y -= ceil(offset);
}
self.myTextView.frame = frame;
}
completion:^(BOOL finished) {
/* completion code here */
}
];
return YES;
}
您应该始终检查contentSize
是否大于的frame Height
。
这就是你textView
不断增长的原因
希望这能解决你的问题!