UITextField text change event

后端 未结 21 1040
南方客
南方客 2020-11-22 06:49

How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly.

21条回答
  •  花落未央
    2020-11-22 07:21

    One thing is you may have multiple UITextFields. So, give them a tag and then you can switch on the tags. Here's how to setup an observer in any class pretty much.

    private func setupTextFieldNotification() {
        NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nil, queue: OperationQueue.main) { (notification) in
            if let textField = notification.object as? UITextField, textField.tag == 100, let text = textField.text {
                print(#line, text)
            }
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    

提交回复
热议问题