Search code examples
iosswiftuitextfieldnsnotificationcenteruitextfielddelegate

Capture delegate methods from UITextField subclass without being the delegate


I have a UITextField subclass. I needed to know when text did change and I was able to get that with NotificationCenter and observing .UITextFieldTextDidChange but now I need to know when the user tap return button. The only solution that I can think about it is setting the UITextField subclass to be the delegate of it self, but it sound not clean.

  1. Is there a clean way to get the return key event from subclass
  2. Is it Ok to to set the UITextField subclass to be the delegate of it self ?

Solution

  • In your subclass do

    self.addTarget(self, action: #selector(returnKeyPressed), for: .editingDidEndOnExit);
    

    Looking at Apples doc you see UIControlEvents

    UIControlEventEditingDidEndOnExit = 1 << 19, // 'return key' ending editing