Jon Buckley
Jon Buckley

Reputation: 117

Keyboard height giving 0 on first load - Swift

I am trying to move the view up when the keyboard appears, using the following code:

func keyboardWillShow(notification: NSNotification) {
if let keyboardSize: CGSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {

            if self.view.frame.origin.y == 0{
                print("Keyboard height is: \(keyboardSize.height)")

                let keyboardHeight = keyboardSize.height - (self.tabBarController?.tabBar.frame.height)!
                self.view.frame.origin.y -= (keyboardHeight)
                print("Keyboard height is: \(keyboardSize.height)")

        }
    }
}

The first time this function is called once the app has been opened, keyboard height is populated as 0, meaning the view drops by the height of the tabBar. When I reload the view, it works perfectly from then on.

It seems like I am not getting the keyboard height until the keyboard is actually opened, which is too late for the first run of the function.

Any idea what the issue is? Please let me know if you want any more details.

Upvotes: 2

Views: 1708

Answers (4)

abhinavroy23
abhinavroy23

Reputation: 3900

This is because you're trying to access keyboardHeight before the keyboard is shown.

Listen to keyboardDidShow(:) instead of keyboardWillShow(:) and you'll get the correct keyboard height.

use this instead:

func keyboardDidShow(notification: NSNotification) {
if let keyboardSize: CGSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size {
       //DO YOUR STUFF
} }

Upvotes: 0

Hiren Panchal
Hiren Panchal

Reputation: 3023

For swift 3.0 and above

@objc private func keyboardWillShow(_ notification: Notification){
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
{
  print("keyboardSize.height = ",keyboardSize.height)
}  }

Upvotes: 1

Mohamed Helmy
Mohamed Helmy

Reputation: 832

I am using this

first

var iskeyboard : Bool = false;

for show

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

        if (!iskeyboard)
        {
            self.view.frame.origin.y -= keyboardSize.height
        }
        iskeyboard = true

    }
}

for hide

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

        if (iskeyboard)
        {
            self.view.frame.origin.y += keyboardSize.height
        }
         iskeyboard = false
    }
}

Upvotes: 0

Daniel T.
Daniel T.

Reputation: 33967

Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey and see if that helps.

Upvotes: 10

Related Questions