我有下面的这段代码,它在调用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。基本上,每当我单击textFields之一时,都会调用该键盘通知,并且其中的代码keyboardWillShow将运行。我知道我if...let发表了声明,但我想知道为什么我对此一无所获。
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])
从文档:
let UIKeyboardFrameEndUserInfoKey: String
描述 包含CGRect的NSValue对象的键,该键在屏幕坐标中标识键盘的末端框架
描述
包含CGRect的NSValue对象的键,该键在屏幕坐标中标识键盘的末端框架
您的第二把钥匙:
let UIKeyboardAnimationDurationUserInfoKey: String
说明NSNumber对象的键,该键包含一个以秒为单位标识动画持续时间的double。
因此,您需要将第一个强制转换为NSValue,第二个强制转换为NSNumber:
func keyboardWillShow(_ notification: Notification) { print("keyboardWillShow") guard let userInfo = notification.userInfo else { return } keyboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue animaton = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue // your code }