2

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
    }
}
mpc75
  • 937
  • 9
  • 22
  • Does this answer your question? [Changing a custom UIView background when selected](https://stackoverflow.com/questions/23521912/changing-a-custom-uiview-background-when-selected) – koen May 11 '20 at 15:18
  • @koen thanks for the suggestion but it did not. overriding ```touchesBegan``` worked but when I select another field I want the border to return to normal and neither overriding ```touchesEnded``` nor ```touchesCancelled``` solved this. – mpc75 May 11 '20 at 15:31

1 Answers1

2

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.

TylerP
  • 9,600
  • 4
  • 39
  • 43