【发布时间】:2025-12-28 08:40:05
【问题描述】:
我有一个TextView。当键盘出现时,TextView 的一部分隐藏在键盘后面。因此,我通过降低其底部约束(及其父视图的底部)来降低其高度,以便用户可以滚动并查看整个文本。
但问题是当键盘消失时,它不会将 TextView 的高度调整为原始高度。但是当我点击它时,它会显示与第一张图片相同的整个文本。
正常的样子:
键盘出现后的样子:
键盘消失后的样子:
现在,如果我点击TextView,它看起来与第一张图片相同。即调整大小以具有适当的大小:
代码: self.messageView 是 TextView。
// Called when keyboard is going to be displayed
- (void)keyboardWillShow:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// get animation info from userInfo
NSTimeInterval animationDuration;
CGRect keyboardFrame;
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];
// Save constant to set back later
self.bottomConstant = self.noticeMessageBottom.constant;
// Change bottom space constraint's constant
self.noticeMessageBottom.constant = keyboardFrame.size.height + 8.0f;
[UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.messageView setNeedsLayout];
[self.messageView layoutIfNeeded];
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
} completion:nil];
[self.messageView flashScrollIndicators];
}
// Called when keyboard is going to be hidden
- (void)keyboardWillHide:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
// get animation info from userInfo
NSTimeInterval animationDuration;
CGRect keyboardFrame;
[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];
// Reset contentOffset
self.messageView.contentOffset = CGPointZero;
// Change bottom space constraint's constant
self.noticeMessageBottom.constant = self.bottomConstant;
[UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.messageView setNeedsLayout];
[self.messageView layoutIfNeeded];
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
} completion:nil];
}
更新:我将背景颜色设置为TextView,并看到高度已正确更改,但部分文本不可见。当我点击它时它会变得可见。
注意: 仅当TextView 的contentOffset 是(0,0) 时才会发生这种情况。即用户没有滚动它。如果用户滚动它并且contentOffset 不是(0,0) 那么它工作正常。
【问题讨论】:
-
这一行的结果是什么:self.bottomConstant = self.view.bounds.size.height - (self.messageView.frame.origin.y + self.messageView.bounds.size.height) ; ?
-
@LordZsolt 只是保存常量的当前值。编辑问题以使其更清楚。立即检查。
-
我知道它正在保存常量的当前值...呃...我想知道数值...
-
为什么不使用滚动视图?
-
@iBug
TextView是scrollview的子类。它有滚动指示器。
标签: ios objective-c ios7 uitextview autolayout