Adding an observer to a UITextfield. never fires?

696 Views Asked by At

Swift 4.0 iOS 11.x

Added some UITextfields, became the first responder and than these observers. But they never seem to fire? What am I missing here?

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var hintTextField: UITextField!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    listenToTextFields()
}

private func listenToTextFields() {
    let center = NotificationCenter.default
    let queue = OperationQueue.main
    namedObserver = center.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: nameTextField, queue: queue) { (notification) in
        print("You edited \(self.nameTextField.text)")
    }
    hintObserver = center.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: hintTextField, queue: queue) { (notification) in
        print("You edited \(self.hintTextField.text)")
    }
}

When I enter text into the nameTextField or hintTextField, nothing is printed to the console. Tried making the class a UITextFieldDelegate, and indeed setting the textfield delegate, but still no notifications coming my way?

2

There are 2 best solutions below

0
On

Try it with the XCode UI instead of do it via code. See the image below.

enter image description here

0
On

Ok, Got this to work, by using a different notification, used to work it seems; but certainly not doing so at this point.

private func listenToTextFields() {
    let center = NotificationCenter.default
    let queue = OperationQueue.main
    let alert2Monitor = NSNotification.Name.UITextFieldTextDidEndEditing
    namedObserver = center.addObserver(forName: alert2Monitor, object: nameTextField, queue: queue) { (notification) in
      self.setWayPoint.didSetVariable(image: nil, name: self.nameTextField.text, hint: self.hintTextField.text)
    }
    hintObserver = center.addObserver(forName: alert2Monitor, object: hintTextField, queue: queue) { (notification) in
      self.setWayPoint.didSetVariable(image: nil, name: self.nameTextField.text, hint: self.hintTextField.text)
    }
}