user8567812
user8567812

Reputation:

Keyboard show notification called twice using iOS11 Simulator

I'm getting keyboard height using UIKeyboardFrameEndUserInfoKey key like the following:

let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)

and if I tap UITextView, the keyboard comes up, and prints

258.0

then I press ⌘ + k, the simulator connects hardware keyboard, hence software keyboard on the simulator goes down.

And if I press ⌘ + k to make the keyboard up again, keyboardShow notification called twice and prints

216.0
258.0

Why is the keyboard show notification called twice and why 216.0 at first?

Update

This is my entire code.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        notificationCenter.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    @objc func keyboardWillShow(notification: NSNotification) {
        let userInfo = notification.userInfo!
        let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height

        print(keyboardHeight);
    }

    @objc func keyboardWillHide(notification: NSNotification) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

and the results shown if I press ⌘ + k multiple times...

result console image

Upvotes: 2

Views: 839

Answers (1)

Rashwan L
Rashwan L

Reputation: 38833

Not really sure how you have declared your observer, but the following works fine in both Xcode 8 and Xcode 9 beta (iOS 11).

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

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

@objc func keyboardWillShow(sender: NSNotification) {
    let keyboardHeight = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
    print(keyboardHeight)
}

Update:
Just tested your code and it complies and works fine, you must have something else that´s disturbing it.

Output after testing:
226.0
226.0
226.0
226.0
226.0
226.0

Upvotes: 1

Related Questions