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{ ... }
}