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

时间:2015-01-09 18:37:52

标签: ios swift delegates protocols

我有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
    . . .
}

我如何使用"协议方法"或者"我如何检测变化字符"在我的扩展名?

-

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

1 个答案:

答案 0 :(得分:0)

在这种情况下,您需要协议方法。您可以将textFields的委托设置为视图控制器,然后它会随时告诉您文本的更改以及更改的内容。请务必声明您的视图控制器实现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
    }

}
相关问题