Text change notification for an NSTextField

Viewed 42469

I would like to use the code from the answer to this question: How to observe the value of an NSTextField on an NSTextField in order to observe changes on the string stored in the NSTextField.

[[NSNotificationCenter defaultCenter]
    addObserverForName:NSTextViewDidChangeSelectionNotification
    object:self.textView 
    queue:[NSOperationQueue mainQueue] 
    usingBlock:^(NSNotification *note){
    NSLog(@"Text: %@", self.textView.textStorage.string);
}];

The class used here is an NSTextView. I can't find a notification in NSTextField to use instead of NSTextViewDidChangeSelectionNotification.

Is there a notification available in NSTextField that can be used in this case ?

5 Answers

You should use NSTextFieldDelegate and implement controlTextDidChange. Test in macOS 10.14 and Swift 4.2

import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate {

  @IBOutlet weak var textField: NSTextField!

  override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self
  }

  func controlTextDidChange(_ obj: Notification) {
    let textField = obj.object as! NSTextField
    print(textField.stringValue)
  }
}
Related