【发布时间】:2017-01-23 23:51:40
【问题描述】:
下面的代码在调用 keyboardWillShowNotification 时运行:
func keyboardWillShow(_ notification: Notification) {
//ERROR IN THE LINE BELOW
keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
animaton = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.height
})
}
我在第二行收到错误消息:unexpectedly found nil while unwrapping an Optional value。基本上,每当我单击其中一个文本字段时,都会调用此键盘通知,并且keyboardWillShow 中的代码将运行。我知道我放了if...let 声明,但我想知道为什么我会为此得到零。
我不确定我是如何得到这个错误的,或者如何调试它。是不是因为我是在模拟器上运行的?
这是打印 notification.userInfo 给出的内容:
可选([AnyHashable("UIKeyboardFrameEndUserInfoKey"): NSRect: {{0, 315}, {320, 253}}, AnyHashable("UIKeyboardIsLocalUserInfoKey"): 1, AnyHashable("UIKeyboardBoundsUserInfoKey"): NSRect: {{0 , 0}, {320, 253}}, AnyHashable("UIKeyboardAnimationCurveUserInfoKey"): 7, AnyHashable("UIKeyboardCenterBeginUserInfoKey"): NSPoint: {160, 694.5}, AnyHashable("UIKeyboardCenterEndUserInfoKey"): NSPoint: {160, 441.5}, AnyHashable("UIKeyboardFrameBeginUserInfoKey"): NSRect: {{0, 568}, {320, 253}}, AnyHashable("UIKeyboardAnimationDurationUserInfoKey"): 0.25])
【问题讨论】:
-
记录
notification.userInfo。查看实际存在哪些键。 -
哦,让我试试。
-
我在我的问题中添加了打印出来的内容。显示
UIKeyboardFrameEndUserInfoKey可用。 -
当我注释掉这两行时:
keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValueanimaton = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue键盘会正确弹出,也不会出现 nil 错误。 -
只需将其转换为 NSValue 而不是 AnyObject
标签: ios swift swift3 uikeyboard nsnotification