Link to home
Start Free TrialLog in
Avatar of STEVEN WEBBER
STEVEN WEBBERFlag for United States of America

asked on

TextField Changed Notification Problem

I am trying to run code in swift when a textField (in macOS) changes. I have tried:

    override func viewDidLoad() {
        super.viewDidLoad()

        let name = "NSNotificationTextFieldChanged"
        NotificationCenter.default.addObserver(self, selector: Selector(fieldTextDidChange),
            Notification(name: Notification.Name(rawValue: name)), object: nil)
       
    }
   
    func fieldTextDidChange(notification: NSNotification) {
        errorMessage.stringValue = ""
        errorMessage.isHidden = true
    }

but I get the error "Cannot convert value of type '(NSNotification) -> ()' to expected argument type 'String'

Any ideas?
Avatar of Hamidreza Vakilian
Hamidreza Vakilian

I don't think adding observers is the proper way. Try this way:

Swift:
textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)

Open in new window

and
 func textFieldDidChange(textField: UITextField) {
    //your code
}

Open in new window


Swift 2.2:
textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

Open in new window

and
func textFieldDidChange(textField: UITextField) {
    //your code
}

Open in new window


Swift 3:
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

Open in new window

and
func textFieldDidChange(_ textField: UITextField) {
//do something here
}

Open in new window

Avatar of STEVEN WEBBER

ASKER

Thanks Hamidreza Vakilian. I will try this.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.