5

I am trying to implement a reusable UITextFieldDelegate class as follows:

class CustomTextFieldDelegate : NSObject, UITextFieldDelegate

All delegate protocol methods are implemented correctly.

In the controller, I assign the delegate to the UITextField

textField.delegate = CustomTextFieldDelegate()

The problem is that none of the delegate functions get called. However, when I implement the delegate protocol from the controller, then things work fine

class CustomTableViewController: UITableViewController, UITextFieldDelegate

Any ideas what is going on?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
Joe.b
  • 422
  • 1
  • 6
  • 16

1 Answers1

6

If your want to reuse CustomTextFieldDelegate through out the project, you should use a Singleton instance;

textField.delegate = CustomTextFieldDelegate.sharedInstance

and the class changes

class CustomTextFieldDelegate : NSObject, UITextFieldDelegate {

    static let sharedInstance:CustomTextFieldDelegate = CustomTextFieldDelegate();

    func textFieldDidBeginEditing(textField: UITextField) {
        NSLog("textFieldDidBeginEditing ...");
    }
   //... other methods
} //F.E.
Shoaib
  • 2,286
  • 1
  • 19
  • 27
  • I'm not trying to inherit a protocol. Rather, I'm trying to create a reusable delegate that I can use on many text fields. – Joe.b Oct 08 '15 at 15:22
  • @Joe.b checkout my updated answer. it's working tested on swift 1.2 – Shoaib Oct 08 '15 at 17:58
  • This did it. Thank you. Can you please explain why singleton works but creating an object does not? – Joe.b Oct 08 '15 at 20:33
  • As @Horst already mentioned above in his comment, the issue is you are not retaining the instance of CustomTextFieldDelegate anywhere so losing it. – Shoaib Oct 09 '15 at 04:51