我有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},从而破坏滚动。我已经添加了一个hack到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;
}
任何人都知道如何完全避免这个问题?
答案 0 :(得分:1)
我不知道您的代码有什么问题,如果您愿意,我们可以详细处理。但作为初步建议,如果可能,请不要调整UITextView的大小:只需更改其内容并滚动插入内容,如下所示:
- (void) keyboardShow: (NSNotification*) n {
NSDictionary* d = [n userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
self.tv.contentInset = UIEdgeInsetsMake(0,0,r.size.height,0);
self.tv.scrollIndicatorInsets = UIEdgeInsetsMake(0,0,r.size.height,0);
}
即便如此,我发现你必须等到键盘隐藏动画完成才能重置这些值:
- (void) keyboardHide: (NSNotification*) n {
NSDictionary* d = [n userInfo];
NSNumber* curve = d[UIKeyboardAnimationCurveUserInfoKey];
NSNumber* duration = d[UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:duration.floatValue delay:0
options:curve.integerValue << 16
animations:
^{
[self.tv setContentOffset:CGPointZero];
} completion:^(BOOL finished) {
self.tv.contentInset = UIEdgeInsetsZero;
self.tv.scrollIndicatorInsets = UIEdgeInsetsZero;
}];
}
(可能这个技巧也会以某种方式帮助你的代码。)