简体   繁体   中英

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

I am using this code to scroll the view up when I start editing a 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
        }
    }
}

However, I also have a UITextField at the top of this view, and the view also scrolls when I begin editing it. I do not want this to happen. How can I change my code to only scroll when the UITextView keyboard is active and not when the UITextField keyboard is activated?

Try this piece of code, user textview delgate

// scrollBy - pass the height you want your scrollview to be scrolled when keyboard appears

 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而不是编码,这会在需要时切换键盘

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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