Ios 类扩展中的调用委托方法,Swift

Ios 类扩展中的调用委托方法,Swift,ios,swift,delegates,protocols,Ios,Swift,Delegates,Protocols,我有UITextField类扩展: extension UITextField { ... } 类UITextField还具有协议: protocol UITextFieldDelegate : NSObjectProtocol { . . . optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString st

我有UITextField类扩展:

extension UITextField {
    ...
}
类UITextField还具有协议:

protocol UITextFieldDelegate : NSObjectProtocol {
    . . .
    optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
    . . .
}
如何使用协议方法或如何检测扩展名中的更改字符

-


我的主要目标是检测角色变化范围

在这种情况下,您需要协议方法。您可以将文本字段的委托设置为您的视图控制器,然后它会在任何时候通知您文本的更改及其更改内容。确保声明视图控制器实现UITextFieldDelegate方法。下面是一个检测文本字段更改的视图控制器示例

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // this allows the shouldChangeCharactersInRange method to be called
        self.textField.delegate = self  
    }

    // UITextFieldDelegate method
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        // range is the range of which characters changed
        // string is the characters that will replace the textField.text's characters in the given range
        return true
    }

}

您是否试图在文本字段发生更改时得到通知以及更改的文本是什么,或者您是否试图添加自己的功能来替换文本字段、shouldChangeCharactersRange、replacementString?我希望以任何方式检测字段中更改的字符。UITextField允许使用这3个通知:let UITextFieldTextDidBeginEditingNotification:NSString!让UITextFieldTextDidEndEditingNotification:NSString!让UITextFieldTextDidChangeNotification:NSString!但这还不够。我的主要目标是检测角色变化范围。泰克斯,我认为这是正确的方向。但现在我有另一个问题:-当我使用UITextFieldDelegate协议在单独的文件中创建子类并使用适当的方法时。一切顺利。但如果有人想在ex.ViewController类中使用UITextFieldDelegate,我的协议方法将被new覆盖。我需要更多详细信息。子类是ViewController吗?是否有多个文本字段连接到ViewController,这些字段都依赖于ShouldChangeCharactersRange?Thx以获取帮助。这里是新的问题链接