gpt4 book ai didi

ios - 在展开可选值 keyboardWillShow 时意外发现 nil

转载 作者:可可西里 更新时间:2023-11-01 00:36:15 25 4
gpt4 key购买 nike

我有下面这段代码,它在调用 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 语句,但我想知道为什么我为此得到了 nil。

我不确定我是如何得到这个错误的,也不知道如何调试它。是因为我是从模拟器上运行的吗?

这是打印 notification.userInfo 的结果:

Optional([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 

Description

The key for an NSValue object containing a CGRect that identifies the end frame of the keyboard in screen coordinates

你的第二把 key :

let UIKeyboardAnimationDurationUserInfoKey: String

Description The key for an NSNumber object containing a double that identifies the duration of the animation in seconds.

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

关于ios - 在展开可选值 keyboardWillShow 时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39519822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com