AJ Z.
AJ Z.

Reputation: 495

Keyboard height 0

I am trying to move a stackview above the keyboard when user is typing.I am using the following code to get the height of the keyboard (taken from Move view with keyboard using Swift).

The first time the keyboard appears, the code works,keyboardSize.height prints out to be 226.0. However, when the keyboard reappears after the first time, keyboardSize.height prints out to be 0.0. As a result, I am having trouble consistently moving my stackview up when the keyboard appears. Occasionally, the code would work again after the first try, but it does not last more than one time, and behaves inconsistently.

When I simply print out keyboardSize, the first time I would get (0.0, 736.0, 414.0, 226.0). After the first time, keyboardSize prints out to be (0.0, 736.0, 414.0, 0.0), so only the height becomes incorrect.

How could I get the height of the keyboard consistently? Why is this issue occurring?

override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue{
        print(keyboardSize.height)
        ...
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue{ ... }
}

Upvotes: 1

Views: 433

Answers (3)

Bhadresh Baraiya
Bhadresh Baraiya

Reputation: 21

Use this code:

CGSize keyboardSize = 
  [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

Upvotes: 0

ali ozkara
ali ozkara

Reputation: 5646

Use this;

UIKeyboardFrameEndUserInfoKey

Objective C;

CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

Upvotes: 1

Sand'sHell811
Sand'sHell811

Reputation: 388

If you are showing the stack view above keyboard using input accessory view and you have canBecomeFirstResponder of accessory view to true than when the keyboard appears firt time then it'll give you original height but when you close the keyboard tgen incase of accessoryview usage first it goes to keyboard close notification and the again to keyboard open notification function. So you'll be getting keyboard open height on closing also. Use breakpoints in both functions to confirm it and solve your problem by using some check variables. Note****** must read about input accesory view best way to add view above keyboard like in chat apps.

Upvotes: 0

Related Questions