Subclass SWIFT UITextField Handles Program Changes

I have a subclass of UITextField that is specific for processing date text. I have a tableviewcell that uses this text box:

 let dateInput: DateTextField 

Now the controller should initialize the text dateInput before displaying as follows:

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

Now I want to be able to detect that the text has been changed from a subclass, so that I can update the internal date variable so that it synchronizes with the text.

I have implemented text field delegation methods, but it just catches the changes made by the user, not programmatically.

+7
ios swift nsdate
Jan 29 '16 at 9:53 on
source share
3 answers

You can override the property and add didSet observer to your own class:

 class DateTextField: UITextField { override var text: String? { didSet { // Do your stuff here } } } 
+5
Jan 29 '16 at 22:30
source share

My solution for this is to have each instance of the subclass maintain its own notification for UITextFieldDidChange and use its own protocol to pass this 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 ...

+3
Oct 05 '17 at 9:36 on
source share

Check the UIControlEventEditingChanged event ... inside it you can set the following logic.

Example from this post:

 // Add a "textFieldDidChange" notification method to the text field control. [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; 
+2
Jan 29 '16 at 21:56
source share



All Articles