简体   繁体   中英

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.

使用UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey ,看看是否有帮助。

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)
}  }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM