【问题标题】:UIScrollView do not scroll down to its original position when keyboard disappear键盘消失时,UIScrollView 不会向下滚动到其原始位置
【发布时间】:2017-10-19 18:31:58
【问题描述】:

我面临着非常奇怪的情况。当键盘出现在某些 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) {
    }];
}

【问题讨论】:

    标签: ios objective-c uiscrollview


    【解决方案1】:

    我会盲目地尝试使用UIKeyboardFrameEndUserInfoKey 而不是UIKeyboardFrameBeginUserInfoKey 看看它是否有效。

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

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

    【讨论】:

    • 我的错,正确的是self.detailCommentView.frame.origin.y。让我现在编辑它,也感谢您的回复。让我检查它是否有效。
    • 我无法理解您解决方案的第一部分。请你分享一些代码。谢谢
    • 我会尝试在您的代码中将UIKeyboardFrameBeginUserInfoKey 替换为UIKeyboardFrameEndUserInfoKey,看看它是否有效
    • 我已经更换了它,但什么也没发生。 commentViewFrame 值也是正确的。
    【解决方案2】:

    我找到了解决方案。实际上,滚动视图背后的概念对我来说并不清楚。但现在很清楚,只改变一行就成功了。

    - (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) {
        }];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 2012-12-03
      • 2017-08-11
      • 1970-01-01
      • 2015-02-16
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多