繁体   English   中英

当键盘显示UITextView而不是同一视图上的UITextField时,滚动视图

[英]Scroll view when keyboard appears for UITextView, but not for the UITextField that's on the same view

当我开始编辑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键盘时滚动?

尝试这段代码,用户使用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);
    }

我建议您应该在项目中添加TPkeyboard File而不是编码,这会在需要时切换键盘

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM