Swift UITextField subclass handle text change programmatically

My solution for this is to have each instance of the subclass maintain its own notification for UITextFieldDidChange and use a custom protocol to relay that information to the listener.

protocol MutableTextFieldDelegate {
    func textChanged(_ sender:MutableTextField)
}

class MutableTextField : UITextField {

    var textChangedDelegate : MutableTextFieldDelegate?

    var previousValue : String?

    override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(forName: .UITextFieldTextDidChange, object: self, queue: nil) { [weak self] notification in
            guard let strongSelf = self else { return }
            guard let object = notification.object as? MutableTextField, object == strongSelf else { return }

            if strongSelf.previousValue != strongSelf.text {
                strongSelf.textChangedDelegate?.textChanged(strongSelf)
            }
            strongSelf.previousValue = strongSelf.text
        }
    }
}

swift5: NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification ...


You can override property and add didSet observer in your custom class:

class DateTextField: UITextField {

    override var text: String? {
        didSet {
           // Do your stuff here    
        }
    }   
}

Tags:

Ios

Nsdate

Swift