如何将目标添加到 ViewController 之外的类中的 UITextField
我正在尝试编写一个类,该类具有观察 UITextField 对象上的文本更改的方法。
在 ViewController 中时,下面的代码按预期工作:
class ViewController: UIViewController {
@IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(view, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
所以我编写了一个类并将方法放入其中,如下所示:
internal class ListenerModule: NSObject, UITextFieldDelegate {
internal func textWatcher(textField: UITextField!, view: UIViewController!) {
textField.delegate = self
textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
@objc internal func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
//And in ViewController,
...
ListenerModule().textWatcher(textField: password, view: self)
...
但它不起作用。
如何将目标添加到类或库中的文本字段?
I am trying to write a class that has a method which observe text changes on UITextField objects.
When in ViewController, code below works as intended:
class ViewController: UIViewController {
@IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(view, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
So i wrote a class and put methods in it as below:
internal class ListenerModule: NSObject, UITextFieldDelegate {
internal func textWatcher(textField: UITextField!, view: UIViewController!) {
textField.delegate = self
textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
@objc internal func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
//And in ViewController,
...
ListenerModule().textWatcher(textField: password, view: self)
...
But it does not work.
How can i add target to a TextField in a class or a library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这可能是因为您没有坚持使用
ListenerModule
对象。我相信您正在某个函数中执行此
ListenerModule().textWatcher(textField: password, view: self)
,因此创建的对象的范围仅限于该函数。您可以执行以下操作:
尝试一下,看看这是否可以解决您的问题
I think it could be because you are not persisting with your
ListenerModule
object.I believe you are doing this
ListenerModule().textWatcher(textField: password, view: self)
in some function so the scope of the object created is limited to that function.You could do the following:
Give this a try and see if this solves your issue