0

我正在尝试编写一个具有观察 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)
...

但它不起作用。

如何将目标添加到类或库中的 TextField?

4

1 回答 1

0

我认为这可能是因为你没有坚持你的ListenerModule对象。

我相信您是ListenerModule().textWatcher(textField: password, view: self)在某个函数中执行此操作的,因此创建的对象的范围仅限于该函数。

您可以执行以下操作:

// 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)
}

试一试,看看这是否能解决您的问题

于 2022-02-24T04:17:18.197 回答