Change UITextField background when editing begins

Giles Van Gruisen picture Giles Van Gruisen · Jan 3, 2010 · Viewed 18k times · Source

I'd like to change the background image of a UITextField when it becomes the firstResponder to show the user that it has focus, similar to the :active or :focus pseudo-classes in CSS.

I'm guessing that I may need to do this programmatically; so any help is greatly appreciated.

-Giles

Answer

Ziconic picture Ziconic · Jul 26, 2012

The cleanest way IMHO is to subclass UITextField and override becomeFirstResponder and resignFirstResponder to change the background image of the text field. That way, you can use your new subclass anywhere without having to reimplement the delegate methods to change the background.

- (BOOL)becomeFirstResponder {
    BOOL outcome = [super becomeFirstResponder];
    if (outcome) {
      self.background = // selected state image;
    }
    return outcome;
}

- (BOOL)resignFirstResponder {
    BOOL outcome = [super resignFirstResponder];
    if (outcome) {
      self.background = // normal state image;
    }
    return outcome;
}