Swift: Recognize when UITextField is enabled


I am new to swift and have been stuck on this for hours. I am trying to recognize when a UITextField is tapped by the user, and call some function. For some reason I keep getting "unrecognized selector sent to instance". Here is my attempt at a solution

and Here is the error thrown

Any help is greatly appreciated!

Your selector is not pointing to the method! Try this instead:

textField.addTarget(self, action: #selector(ViewController.tapped(_:)), for: UIControlEvents.touchDown)

Also, instead of this approach you could also set ViewController as the delegate for textField and implement this:

extension ViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.backgroundColor = UIColor.blue