Latcie
Latcie

Reputation: 701

keyboardWillHide notification malfunction

I have:

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

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

}

And also:

func keyboardWillShow(notification: NSNotification) {

    if (self.view.center.y == maxPointY){
        self.view.frame.origin.y -= maxPointY/2
    }
}

func keyboardWillHide(notification: NSNotification) {

    self.view.frame.origin.y += maxPointY/2
}

The problem is that when I click on a textfield that should pop up the keyboard, keyboardWillHide gets called.

I have this as well:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    usernameTextField.resignFirstResponder()
    passwordTextField.resignFirstResponder()
    textField.resignFirstResponder()
    return true
}

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

Upvotes: 0

Views: 91

Answers (2)

Latcie
Latcie

Reputation: 701

It was this tidbit:

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

I didn't call super.touchesBegan. I had to change it to:

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

Upvotes: 1

KKRocks
KKRocks

Reputation: 8322

Try this : Swift 3

It is working in my side . I think you have passed selector without arguments

 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)

Selector

func keyboardWillShow(notification: NSNotification) {
    }

func keyboardWillHide(notification: NSNotification) {
     }

Delegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

Upvotes: 1

Related Questions