2015-01-09 76 views
0

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

如何使用“协议法”或“我怎么能检测到更改字符“在我的扩展?

-

我的主要目标是发现性格改变的范围。

+0

你们是不是在文本字段改为得到通知,什么文字是变化的,或者是你想添加自己的功能来代替'文本框(_,shouldChangeCharactersInRange,replacementString)'? – keithbhunter 2015-01-09 18:57:49

+0

我希望以任何方式检测字段中的变化字符。 UITextField允许使用这3个通知:'让UITextFieldTextDidBeginEditingNotification:NSString! let UITextFieldTextDidEndEditingNotification:NSString!让我们使用UITextFieldTextDidChangeNotification:NSString!',但这还不够。我的主要目标是检测字符改变的范围。 Thx – 2015-01-10 09:22:48

回答

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 
    } 

} 
+0

是的,我认为这是正确的方向。但现在我有另一个问题: - 当我用UITextFieldDelegate协议创建我的子类在单独的文件并使用适当的方法。所有作品。但是如果有人想在ex中使用UITextFieldDelegate。 ViewController类,我的协议方法将被新的覆盖。 – 2015-01-12 12:47:17

+0

我需要更多的细节。是子类ViewController?是否有连接到ViewController的多个文本字段都将依赖'shouldChangeCharactersInRange'? – keithbhunter 2015-01-12 21:22:08

+0

Thx为您提供帮助。这里是新的问题链接http://stackoverflow.com/questions/27928392/call-protocol-method-twice-swift – 2015-01-13 17:53:59