Call protocol method twice, Swift

耗尽温柔 提交于 2019-12-12 04:58:56

问题


I have subclass file which use method from UITextFieldDelegate protocol

class MyTextField: UITextField, UITextFieldDelegate {
     . . .
     override func willMoveToSuperview(newSuperview: UIView?) {
         super.willMoveToSuperview(newSuperview)

         self.delegate = self       
     }

     func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

         // some actions

         return true
     }
}

In my ViewController class I use input field with my subclass

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var field: MyTextFieldMask!

    override func viewDidLoad() {
         super.viewDidLoad()
         // Do any additional setup after loading the view, typically from a nib.

          self.field.delegate = self

     }
     func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

         // some other actions

         return true
     }
}

If somebody add UITextFieldDelegate protocol method to ViewController class (like on code above) my first method in MyTextField subclass will be overwritten.

How I can use same method twice with different actions inside?


回答1:


Just pass it through if you want it to execute. You'll need to implement all of the delegate protocol methods, even if they just end up being pass-throughs. Example:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

     // some other actions

     self.field.textField(self.field, range, string)

     return true
 }

Making an object be a delegate of itself is dangerous practice to begin with and can lead to reference cycles. You should consider refactoring your code to accomplish your task in a different way.



来源:https://stackoverflow.com/questions/27928392/call-protocol-method-twice-swift

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