Getting Fatal Error with UITextFieldDelegete

I have setup a UITextField in a ViewController and Xcode doesn't show me errors. But when I run my app and load the Screen the app crashes with the error message:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

This is my code:

import UIKit

class LoginScreenViewController: UIViewController, UITextFieldDelegate{
    
    @IBOutlet weak var phoneAndEmailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        phoneAndEmailTextField.delegate = self
        passwordTextField.delegate = self
    }

    @IBAction func phoneAndEmailTextFieldAction(_ sender: UITextField) {
        phoneAndEmailTextField.endEditing(true)
        print(phoneAndEmailTextField.text!)
    }

    @IBAction func passwordTextFieldAction(_ sender: UITextField) {
        passwordTextField.endEditing(true)
        print(passwordTextField.text!)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        phoneAndEmailTextField.endEditing(true)
        passwordTextField.endEditing(true)
        
        return true
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text != "" {
            return true
        }else {
            return false
        }
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // sql
    }
}

Where exactly do you get the error ?

In viewDidLoad ? If so, first thing to check:

  • Have you connected properly the 2 IBOutlets ?

If it is in the IBActions:

  • TextField.text may be nil.
  • So replace all unwrap with:
        print(phoneAndEmailTextField.text ?? "No email")

and

        print(passwordTextField.text ?? "No password")
Getting Fatal Error with UITextFieldDelegete
 
 
Q