我有下面的这段代码,它在调用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语句,但是我想知道为什么我对此一无所获。

我不确定如何收到此错误或如何调试它。是因为我正在模拟器中运行它吗?

这是打印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对象的密钥,用于标识
屏幕坐标中键盘的末端框架

您的第二把钥匙:
let UIKeyboardAnimationDurationUserInfoKey: String

描述NSNumber对象的关键字,该对象包含一个
标识动画的持续时间(以秒为单位)。

因此,您需要将第一个强制转换为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
}

09-19 00:14