-1

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. How do I get this to not be of nil value? Do I give my IBOutlet a value instead of using the “!” ?

What this does: Makes the keyboard pop up automatically instead of tapping on the text field (kind of like in spotlight search on 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

Shubham
  • 763
  • 5
  • 20
Joe
  • 69
  • 1
  • 12
  • 1
    How did you init View/VC with that Xib/Storyboard? Is the link done? – Larme Jan 17 '19 at 05:52
  • why don't you put "autoKeyboard.becomeFirstResponder()" this method to viewWillAppear or viewDidAppear? – Shubham Jan 17 '19 at 05:57
  • Why are you overriding this method? – Shubham Jan 17 '19 at 05:58
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Jan 17 '19 at 06:25

2 Answers2

0

The reason you are getting a nil value is because your nib has not been initialized yet, thus your textfield is nil. I think you are calling your becomeFirstResponder on your textfield too early in the view controller life cycle.

Mocha
  • 2,035
  • 12
  • 29
-2

I made the IBObject autoKeyboard an optional and thus changed the line of code to the following:

    override func viewDidAppear(_ animated: Bool) {
    autoKeyboard?.becomeFirstResponder()
}

It now works!

Joe
  • 69
  • 1
  • 12