问题
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