Ben
Ben

Reputation: 9001

Executing different functions on [RETURN] keypress from different text fields

I have two text fields:

@IBOutlet weak var loginEmailInput: UITextField!
@IBOutlet weak var loginPasswordInput: UITextField!

When the loginEmailInput is active and the return key is pressed, I just want to close the keyboard:

func textFieldShouldReturn(loginEmailInput: UITextField) -> Bool {
    loginEmailInput.resignFirstResponder()
    return true
}

When the loginPasswordInput is active and the return key is pressed, I want to also execute the function loginButtonPressed(...):

func textFieldShouldReturn(loginPasswordInput: UITextField) -> Bool {
    loginPasswordInput.resignFirstResponder()
    loginButtonPressed(self)
    return true
}

However, I receive an error stating that I've now redeclared the textFieldShouldReturn function:

Invalid redeclaration of 'textFieldShouldReturn'

How can I handle the [return] key being pressed with different text fields active?

Upvotes: 3

Views: 93

Answers (1)

luk2302
luk2302

Reputation: 57184

You have to define the function once and branch depending on the given sender:

func textFieldShouldReturn(sender: UITextField) -> Bool {
    if sender == loginEmailInput {
        sender.resignFirstResponder() // or loginEmailInput.resignFirstResponder()
        return true
    } else if sender == loginPasswordInput {
        sender.resignFirstResponder() // or loginPasswordInput.resignFirstResponder()
        loginButtonPressed(self)
        return true
    }
}

Alternatively use a switch case:

func textFieldShouldReturn(sender: UITextField) -> Bool {
    switch sender {
    case loginEmailInput:
        sender.resignFirstResponder() // or loginEmailInput.resignFirstResponder()
    case loginPasswordInput:
        sender.resignFirstResponder() // or loginPasswordInput.resignFirstResponder()
        loginButtonPressed(self)
    default:
        break
    }
    return true
}

If you want to remove as much redundancy as possible you could even use:

func textFieldShouldReturn(sender: UITextField) -> Bool {
    if sender == loginPasswordInput {
        loginButtonPressed(self)
    }
    return true
}

The reason the textFieldShouldReturn gets a sender passed along is exactly for this kind of situations. It is a common pattern for delegates functions to get the object passed along from where the delegate methods gets invoked to make the receiver respond to multiple instances at once.

Upvotes: 3

Related Questions