Home > Back-end >  How to add target to UITextField in a class other than ViewController
How to add target to UITextField in a class other than ViewController

Time:02-25

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?

CodePudding user response:

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

  • Related