呼叫协议方法两次,Swift [英] Call protocol method twice, Swift

查看:179
本文介绍了呼叫协议方法两次,Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用UITextFieldDelegate协议使用方法的子类文件

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
     }
}

在我的ViewController类中,我使用输入字段与我的子类

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
     }
}






如果有人向ViewController类添加UITextFieldDelegate协议方法(如上面的代码),MyTextField子类中的第一个方法将被覆盖。


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?

推荐答案

p>如果你希望它执行,只需传递它。您将需要实现所有的委托协议方法,即使它们只是最终被传递。示例:

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.

这篇关于呼叫协议方法两次,Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆