为UITextView显示键盘时的滚动视图,但不适用于同一视图上的UITextField

时间:2017-01-12 04:56:36

标签: ios swift keyboard uitextfield uitextview

当我开始编辑UITextView时,我正在使用此代码滚动视图。

override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

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

但是,我在此视图的顶部也有一个UITextField,当我开始编辑它时,视图也会滚动。我不希望这种情况发生。如何将代码更改为仅在UITextView键盘处于活动状态时滚动,而不是在UITextField键盘激活时滚动?

2 个答案:

答案 0 :(得分:1)

试试这段代码,用户textview delgate

// scrollBy - 传递键盘出现时滚动滚动视图的高度

 func textViewDidBeginEditing(_ textView: UITextView)
    {
         scrView.setContentOffset(CGPoint.init(x: 0, y: scrollBy), animated: true)

     }

    func textViewDidEndEditing(_ textView: UITextView)
    {
        scrView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)

        self.view.endEditing(true);
    }

答案 1 :(得分:-3)

而不是编码我建议您在项目中添加TPkeyboard文件,这将在需要时切换键盘