1

NSNotification.Name.UIKeyboardWillShow works fine Apple keyboard, But when I Gboard the NSNotification.Name.UIKeyboardWillShow is called 3 times.

Below is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

@objc func keyboardWillHide(notification: Notification) {
    self.view.frame.origin.y = 0
}

@objc func keyboardDidShow(notification: Notification) {
    let info: NSDictionary = notification.userInfo! as NSDictionary
    let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboardY = self.view.frame.height - keyboardSize.height
    let editingTextFieldY = self.reviewTextField.frame.origin.y
    // This below 8 is the bottom constraint of the reviewTextField
    let padding: CGFloat = self.reviewTextField.frame.height+8

    if self.view.frame.origin.y >= 0 {
        if editingTextFieldY > keyboardY - padding {
            let yOffset = self.view.frame.origin.y - (editingTextFieldY - (keyboardY - padding))
            self.view.frame.origin.y = yOffset
        }
    }
}
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57
  • I think I know what the problem might be. When you click a textField and the native keyboard shows up, the observer triggers the action. When you change the standard keyboard to a customs keyboard (Gboard), it closes the native keyboard and shows the custom one in a fraction of a second, thus triggering keyboardWillHide and again keyboardWillShow. This happened to a custom keyboard my teammate was working on. I am not sure how to solve this problem. – Starsky Jul 19 '18 at 08:24
  • Thanks @Starsky for the help!! – Anirudha Mahale Jul 20 '18 at 07:16
  • Did you find a solution for this? – Starsky Jul 20 '18 at 13:08
  • @Starsky Not yet, still am trying. – Anirudha Mahale Jul 20 '18 at 15:38

0 Answers0