Swift reusable UITextFieldDelegate

◇◆丶佛笑我妖孽 提交于 2019-12-23 12:35:04

问题


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:


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.


来源:https://stackoverflow.com/questions/33006082/swift-reusable-uitextfielddelegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!