Question

So I found this thread a while ago: Change UITextField background when editing begins

The top answer is a fantastic resource for changing the background image of a textField when the user edits it. However, my issue is, how can you enable this with MULTIPLE text fields?

Specifically (for my app) I have a login and password field. Using the code I'll post below I can get my first text field to change images correctly when the user taps it. However, I cannot get the next field to follow suit when the user taps either the next text field or the "Next" option on the keyboard. As you can only have one instance of "textFieldShouldBeginEditing" as well as ending, you need to set the code for image change for both fields under the same section. however, when I do this, both my fields change when the first field is tapped, and both restore when the second is tapped.

Any ideas on this one excellent community?

Here's some code:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _userNameTextField.background = [UIImage imageNamed:@"login_field_highlighted@2x"];
    return YES;
    _passwordTextField.background = [UIImage imageNamed:@"password_field_highlighted@2x"];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    _userNameTextField.background = [UIImage imageNamed:@"login_field@2x"];
    return YES;
    _passwordTextField.background = [UIImage imageNamed:@"password_field@2x"];
    return YES;
}

- (BOOL) textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"textFieldShouldReturn");
    if (textField == _userNameTextField) {
        [_passwordTextField becomeFirstResponder];
    } else if (textField == _passwordTextField) {
        [_passwordTextField resignFirstResponder];
    }

    return YES;

}
Was it helpful?

Solution

In each of those methods, you just need to check to see which textfield is targeted, just like you did in textFieldShouldReturn:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == _userNameTextField) {
        _userNameTextField.background = [UIImage imageNamed:@"login_field@2x"];
    } else if (textField == _passwordTextField) {
        _passwordTextField.background = [UIImage imageNamed:@"password_field@2x];
    }
    return YES;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top