How do I make my textField border change to a different color every-time it is selected?

Viewed 233

I've created a custom textField class that I'm using throughout my app, but I want to know how I can change the border color to red every-time a field is selected without having to implement a delegate on each view controller that the textField shows up on.

Is there a way to override a standard function when I'm creating my textField subclass? For buttons, I had success using the following code, but isHighlighted doesn't work for textFields and it doesn't look like I can override isEditing:

override var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? .red : .blue
    }
}
1 Answers

In your UITextField subclass, you can override becomeFirstResponder and resignFirstResponder and perform your changes there:

class YourTextFieldSubclass: UITextField {
    override func becomeFirstResponder() -> Bool {
        let didBecomeFirstResponder = super.becomeFirstResponder()

        if didBecomeFirstResponder {
            layer.borderColor = UIColor.red.cgColor
            layer.borderWidth = 2
            layer.cornerRadius = 5
        }

        return didBecomeFirstResponder
    }

    override func resignFirstResponder() -> Bool {
        let didResignFirstResponder = super.resignFirstResponder()

        if didResignFirstResponder {
            layer.borderColor = UIColor.clear.cgColor
            layer.borderWidth = 0
            layer.cornerRadius = 0
        }

        return didResignFirstResponder
    }
}

Make sure to call super and return that value for both of these overridden methods as in the above example.

Related