NSNotificationCenter Swift 3.0 on keyboard show and hide

后端 未结 9 2214
日久生厌
日久生厌 2020-12-05 19:49

I am trying to run a function when the keyboard shows and disappears and have the following code:

let notificationCenter = NotificationCenter.default
notific         


        
9条回答
  •  天命终不由人
    2020-12-05 19:59

    Swift 4.2+

    @vandana's answer updated to reflect changes to native Notifications in Swift 4.2.

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    
    }
    
    @objc func keyboardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            print("notification: Keyboard will show")
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    
    }
    
    @objc func keyboardWillHide(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0 {
                self.view.frame.origin.y += keyboardSize.height
            }
        }
    }
    

    Also, you need to use UIKeyboardFrameEndUserInfoKey to account for safeAreaInset changes introduced with iOS 11.

提交回复
热议问题