0

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?

Neco
  • 55
  • 1
  • 1
  • 5

1 Answers1

0

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:

// Globally in your UIViewController subclass
var listenerModule: ListenerModule?

// Some set up function after text field is initialized
private func setup()
{
    listenerModule = ListenerModule()

    // Then call the text watcher, not sure why you pass the view,
    // doesn't seem like you use it
    listenerModule?.textWatcher(textField: password, view: self)
}

Give this a try and see if this solves your issue

Shawn Frank
  • 4,381
  • 2
  • 19
  • 29
  • Thanks for your solution. It works now. About the "view" parameter, i use it but i deleted it from example code on purpose. I just forgot to delete from parameters. Thanks. – Neco Feb 24 '22 at 15:07