Search code examples
swiftmacosnstextfield

Swift: Call Function when NSTextField is Edited


I try to dynamically update the text of another view with the changing user input of an NSTextField. The following approach does not work since it is for iOS. Is there something similar for osx NSTextField available?

self.equationTextField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
//build error: "Use of unresolved identifier 'UIControlEvents'"

Thanks!


Solution

  • You will have to make use of NSControlTextEditingDelegate. Connect the NSTextField delegate to your ViewController if you are using storyboard. If you create it programmatically can just set it in code like this: textfield.delegate = self in viewDidLoad()

    In the NSControlTextEditingDelegate there is a controlTextDidChange that you can make use of to get notification when text is edited.

    extension ViewController: NSControlTextEditingDelegate {
        override func controlTextDidChange(_ notification: Notification) {
            if let textField = notification.object as? NSTextField {
                print(textField.stringValue)
                //do what you need here
            }
        }
    }