键盘出现,视图滚动到顶部

时间:2017-11-14 09:33:04

标签: ios swift uitableview scroll keyboard

我的代码有问题:当我点击UITextView并且键盘显示时,有一个滚动到顶部(我真的不知道为什么!) 我必须向下滚动才能返回到UITextView。

我在tableView中,我的细胞有动态高度。

以下是我的问题的一个小演示:

enter image description here

我做了一些研究,我尝试了这个:

   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }

它不会起作用。这真的很奇怪,因为这是我遇到这个问题的唯一观点。

4 个答案:

答案 0 :(得分:0)

如果您对textView有引用,请尝试在keyboardWillShow函数中添加此代码。

scrollView.scrollRectToVisible(textView.frame, animated: true)

答案 1 :(得分:0)

点击UITextView时,它成为第一个响应者,如果您阅读文档,则会明确说明:

  

...某些系统视图(如表视图)可以帮助您自动将第一个响应者滚动到视图中。 ...

这是一个内置功能。<​​/ p>

无论如何,您可以尝试从UITableView删除键盘观察者。

NotificationCenter.default.removeObserver(tableView, name: NSNotification.Name.UIKeyboardWillShow, object: nil)

UITextView

答案 2 :(得分:0)

我遇到过类似的问题。当您向上和向下滚动时,会自动调用scrollViewWillBeginDragging方法。

iOS使用UIScrollViewDelegate来确定用户平移手势的方向。

可能对您有所帮助。

Swift 4

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    let translation: CGPoint = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if translation.y > 0 {
        // react to dragging down
    }
    else {
        // react to dragging up
        view.endEditing(true)
    }
}

目标C

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];

    if(translation.y > 0)
    {
         // react to dragging down

    } else
    {
         // react to dragging up
          [self.view endEditing:YES];
    }
}

答案 3 :(得分:0)

对我来说,解决方案是分离细胞。

在我的情况下,我在一个单元格中有大约3个文本字段,该文本框横跨整个视图。因此,当单击视图底部的文本字段时,我将获得与您完全相同的行为。 (我有一个收藏夹视图)

事实证明,它正在滚动回到单元格的顶部(indexpath.row = 0)。因此,我创建了第二个单元格(indexpath.row = 1),其中仅包含三个文本字段。现在,它正在滚动该单元格的顶部(indexpath.row = 1),这是完美的。

我不知道是什么原因。