Get the height of keyboard doesn't work on IOS 11 beta

社会主义新天地 提交于 2019-12-05 11:12:32

问题


I have the following code which worked on IOS 10, but now it doesn't work anymore when running on IOS 11 beta.

if let userInfo = notification.userInfo {
    if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        print(keyboardSize)
    }
}

This is what I get when I print the size:

(0.0, 0.0, 0.0, 0.0)
(0.0, 736.0, 414.0, 0.0)

Anyone knows why this has stopped working ? Or if I have any other alternatives to get the keyboard size ?


回答1:


Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey

So changing your code to the following will fix your issue:

if let userInfo = notification.userInfo {
    if let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        print(keyboardSize)
    }
}



回答2:


I have the same issue. The answer of Doug Amos is right. I just want to make it clearer. Here is my code:

@objc func keyboardWillShow(notification:NSNotification){

        var userInfo = notification.userInfo!
        var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        if keyboardFrame.size.height <= 0 { // to fix bug on iOS 11
            keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        }
        keyboardFrame = self.view.convert(keyboardFrame, from: nil)
    }



回答3:


I used this code in my app with Swif 3+

    var userInfo = notification.userInfo
    if let keyboardFrame = (userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue{
        print(keyboardFrame.height)
        if keyboardFrame.size.height <= 0 { // To fix bug on iOS 11
            if let newKeyboardFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
                print(newKeyboardFrame.height)
            }
        }
    }
    view.layoutIfNeeded()


来源:https://stackoverflow.com/questions/45570004/get-the-height-of-keyboard-doesnt-work-on-ios-11-beta

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!