[英]I have an error when unwrapping an optional IBOutlet (Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value)
I know why this problem is happening but I don't know how to fix it.我知道为什么会出现这个问题,但我不知道如何解决。 I used an override func to add to the method becomeFirstResponder (which does exactly what it says) from the class ViewController to my IBOutlet
autoKeyboard.我使用了一个覆盖函数来从类 ViewController 到我的IBOutlet
autoKeyboard 添加到方法 becomeFirstResponder(它完全按照它所说的去做)。 How do I get this to not be of nil value?我如何让这不是零价值? Do I give my IBOutlet a value instead of using the “!”我是否给我的 IBOutlet 一个值而不是使用“!” ? ?
What this does: Makes the keyboard pop up automatically instead of tapping on the text field (kind of like in spotlight search on iOS)作用:使键盘自动弹出而不是点击文本字段(有点像 iOS 上的聚光灯搜索)
Let me know if I need to send more information!如果我需要发送更多信息,请告诉我!
override func becomeFirstResponder() -> Bool {
autoKeyboard.becomeFirstResponder()
return true
}
The error I'm given is:我给出的错误是:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value线程 1:致命错误:在展开 Optional 值时意外发现 nil
The reason you are getting a nil value is because your nib has not been initialized yet, thus your textfield is nil.您获得 nil 值的原因是您的笔尖尚未初始化,因此您的文本字段为 nil。 I think you are calling your becomeFirstResponder on your textfield too early in the view controller life cycle.我认为您在视图控制器生命周期中过早地在文本字段上调用了 becomeFirstResponder。
I made the IBObject autoKeyboard an optional and thus changed the line of code to the following:我将 IBObject autoKeyboard 设为可选,因此将代码行更改为以下内容:
override func viewDidAppear(_ animated: Bool) {
autoKeyboard?.becomeFirstResponder()
}
It now works!它现在可以工作了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.