Xcode获取键盘加上建议高度

时间:2018-01-04 10:12:53

标签: swift keyboard

我在获得正确的键盘高度方面遇到了问题。它不会返回键盘加上建议高度。

以下是一些示例代码

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

然后我有一个实用程序方法,它从通知返回键盘框架。代码看起来像这样

 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 = view.convert(keyboardFrame, from: nil)

键盘没有返回键盘高度+建议

我需要这个,因为我正在iPhone 5上进行一些UI测试,在某些屏幕上,键盘会剪切文本字段。所以我有这个代码来检查它是否重叠

// fetches keyboard frame
let keyboardFrame = UtilityMethods.getKeyboardFrame(notification: notification, view: view)

let fieldFrame = lastNameField!.frame

// check if keyboard frame overlaps with field frame
if(keyboardFrame.intersects(fieldFrame)){    
   let newY = view.frame.origin.y - (fieldFrame.origin.y - keyboardFrame.height)
   UtilityMethods.animateViewMoving(viewToAnimate: view, newYValue: newY)
}

但是因为它没有返回键盘+建议的高度,所以if语句失败了。这种方法的唯一方法是,如果我在键盘打开时选择另一个文本字段,然后成为第一个响应者,则它会正确返回键盘高度。

您可以看到我打印出键盘高度

所以当选择fextfield时,打印出这个高度

216.0

然后,如果我选择第二个文本字段,则打印出该高度

253.0

如何确保我始终获得包含建议的keybaord高度?

非常感谢任何帮助。

0 个答案:

没有答案