Swift reusable UITextFieldDelegate

2019-06-26 12:49发布

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?

1条回答
孤傲高冷的网名
2楼-- · 2019-06-26 13:38

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.
查看更多
登录 后发表回答