Search code examples
iosswiftnsdate

Swift UITextField subclass handle text change programmatically


I have a subclass of UITextField that is specific to handle Date text. I have a tableviewcell that uses this text field:

let dateInput: DateTextField

Now the controller needs to initialize the text of the dateInput prior to display as follows:

cell.dateInput.text = "01/29/2016"

Now, I want to be able to detect that the text changed from the subclass so that I can update the internal date variable so that is it in-sync with the text.

I implemented the textfield delegate methods but that just catches changes made by the user and not programmatically.


Solution

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

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