我有这样的代码低于当keyboardWillShowNotification被称为运行:unexpectedly found nil while unwrapping an Optional value
:意外地发现零而展开的可选值keyboardWillShow
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
})
}
我在第二行说得到一个错误。基本上每当我点击其中一个textField时,这个键盘通知就会被调用,并且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'不要使用
as AnyObject
铸造。查看实际存在的密钥。 – rmaddy噢,让我试试。 – CapturedTree
我在问题中添加了什么打印出来。它显示'UIKeyboardFrameEndUserInfoKey'可用。 – CapturedTree