我有一个UITextView
我正在使用它NSLayoutConstraint
来躲避键盘。这是约束:
self.textViewBottomConstraint = [NSLayoutConstraint constraintWithItem:textView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];
[self.view addConstraint:self.textViewBottomConstraint];
当键盘显示/隐藏时,我通过将约束常量设置为键盘高度来为约束设置动画。但是,出于某种原因,这样做会将 contentSize 重置为 {0,0},从而中断滚动。我添加了一个技巧来handleKeyboardDidHide:
将 contentSize 重置为重置之前的值,但这有一些丑陋的副作用,例如滚动位置被重置,并且视图在开始输入之前不会滚动到光标位置。
- (void) handleKeyboardDidShow:(NSNotification *)notification
{
CGFloat height = [KeyboardObserver sharedInstance].keyboardFrame.size.height;
self.textView.constant = -height;
[self.view layoutIfNeeded];
}
- (void) handleKeyboardDidHide:(NSNotification *)notification
{
// for some reason, setting the bottom constraint resets the contentSize to {0,0}...
// so let's save it before and reset it after.
// HACK
CGSize size = self.textView.contentSize;
self.textView.constant = 0.0;
[self.view layoutIfNeeded];
self.textView.contentSize = size;
}
有谁知道如何完全避免这个问题?