0

我有一个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;
}

有谁知道如何完全避免这个问题?

4

1 回答 1

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;
     }];
}

(可能这个技巧也会以某种方式帮助您的代码。)

于 2013-04-11T22:51:43.767 回答