0

I am a totally new to swift. I am trying to set up a screen with 3 textfields so the user can enter data. I used the code line: nameField.delegate = self , but I always get an error message: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value. Could anybody help me fixing that problem? :)

I have already tried to force unwrap the value, but that did not work.

private func configureTextFields(){
       nameField.delegate = self
       amountField.delegate = self
       dateField.delegate = self
   }

I also set up an extension at the bottom. Maybe I did a mistake there:

extension ViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

.

denis_lor
  • 6,212
  • 4
  • 31
  • 55

2 Answers2

1

You should make sure that you aren't calling the configureTextFields function you wrote until viewDidLoad if you are calling it from the initializer, your outlets are not yet set up and will be nil. You probably want your code to look something like this:

override func viewDidLoad() {
     super.viewDidLoad()
     configureTextFields()
}
rpecka
  • 1,168
  • 5
  • 17
0

Make sure you connected your nameField from StoryBoard to your IBOutlet by control-dragging from the StoryBoard to the the variable?

enter image description here

Check Connect UI to the Code from Apple.

denis_lor
  • 6,212
  • 4
  • 31
  • 55