Move UIView up when the keyboard appears in iOS

后端 未结 18 1834
再見小時候
再見小時候 2020-11-28 20:38

I have a UIView, it is not inside UIScrollView. I would like to move up my View when the keyboard appears. Before I tried to use this solution: How can I make a UITextField

18条回答
  •  心在旅途
    2020-11-28 21:00

    Here you go. I have used this code with UIView, though. You should be able to make those adjustments for scrollview.

        func addKeyboardNotifications() {
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(keyboardWillShow(notification:)),
                                                   name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(keyboardWillHide(notification:)),
                                                   name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
    
        func keyboardWillShow(notification: NSNotification) {
    
            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
    // if using constraints            
    // bottomViewBottomSpaceConstraint.constant = keyboardSize.height
    self.view.frame.origin.y -= keyboardSize.height
                UIView.animate(withDuration: duration) {
                    self.view.layoutIfNeeded()
                }
            }
        }
        func keyboardWillHide(notification: NSNotification) {
    
            let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
    //if using constraint
    //        bottomViewBottomSpaceConstraint.constant = 0
    self.view.frame.origin.y = 0
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    

    Don't forget to remove notifications at right place.

    func removeKeyboardNotifications() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    

提交回复
热议问题