当键盘消失时,UIScrollView不会向下滚动到其原始位置

时间:2017-10-19 18:31:58

标签: ios objective-c uiscrollview

我面临着非常奇怪的情况。当键盘出现在某些UITextView上时,我想将UIScrollView向上滚动显示,这部分代码工作正常。但是当键盘消失时,scrollView不会到达其原始位置。当我拖动它然后它到达其原始位置。以下就是我所做的。请指导我错过了什么

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* info = [notification userInfo];
    kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect commentViewFrame = self.detailCommentView.frame;
    commentViewFrame.origin.y += kbSize.height;

    [UIView animateWithDuration:0.3 animations:^{
        [self.detailCommentView setFrame:commentViewFrame];
        self.scrollView.contentOffset = CGPointMake(0, self.detailCommentView.frame.origin.y - 90);
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary* info = [notification userInfo];
    kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect commentViewFrame = self.detailCommentView.frame;
    commentViewFrame.origin.y -= kbSize.height;
    [UIView animateWithDuration:0.3 animations:^{

        [self.detailCommentView setFrame:commentViewFrame];
        self.scrollView.contentOffset = CGPointMake(0, self.detailCommentView.frame.origin.y + 90);
    } completion:^(BOOL finished) {
    }];
}

2 个答案:

答案 0 :(得分:0)

我盲目地尝试使用UIKeyboardFrameEndUserInfoKey代替UIKeyboardFrameBeginUserInfoKey来查看它是否有效。

否则,当您隐藏键盘时,我会检查commentViewFrame值是否正确。

还有一件事我不知道是否正确。在keyboardWillShow您引用self.detailCommentView.frame.origin.y,但在keyboardWillHide中您引用了self.dopDetailCommentView.frame.origin.y。好吗?

答案 1 :(得分:0)

我找到了解决方案。实际上,scrollview背后的概念对我来说并不清楚。但现在很明显,一行中的改变只是伎俩。

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary* info = [notification userInfo];
    kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect commentViewFrame = self.detailCommentView.frame;
    commentViewFrame.origin.y += kbSize.height;

    [UIView animateWithDuration:0.3 animations:^{
        [self.detailCommentView setFrame:commentViewFrame];
        self.scrollView.contentOffset = CGPointMake(0, 0);
    } completion:^(BOOL finished) {
    }];
}