0

The thing I want to implement here is after I press the return key, if text of the textfield is match the word January, print right, if not, print wrong.

But when I pressed the return key, Nothing is printed.

Can anyone write a sample code about how to use DidEndEditing for me?

@IBOutlet weak var wordTextfield: NSTextField!
let monthEN = "January"

func textFieldDidEndEditing(wordTextfield: NSTextField) {
    if wordTextfield.stringValue == monthE{
        print("right")
    }else{

        print("wrong")
    }
}

3 Answers3

1

the textFieldDelegate in os x works like this in Swift 4:

class MainViewController: NSViewController, NSTextFieldDelegate {

      @IBOutlet weak var textFileViewLabel: NSTextField!

      override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.delegate = self
     }



     override func controlTextDidChange(_ obj: Notification) {
         //Here check the changes of textField input
     }

    override func controlTextDidEndEditing(_ obj: Notification) {
        //Here check the changes of textField input

    }
}
0

Presumably, you come from an iOS background and you're just now moving into OS X. I don't have much OS X development experience, but it appears that textFieldDidEndEditing(_:) is not part of the NSTextFieldDelegate protocol.

The NSTextFieldDelegate is simply an extension of NSControlTextEditingDelegate and adds no methods to it.

And with that in mind, it looks like perhaps we need to implement control(_:textFieldShouldEndEditing:) for similar behavior on OS X or potentially control(_:isValidObject:). But either way, it's important to note that NSTextField will never call textFieldDidEndEditing(_:)--that is strictly from iOS.

For more information, I recommend checking out the Apple documentation for NSControlTextEditingDelegate.

And it's also worth mention to make sure you've actually set the text field's delegate property.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • 'func textDidEndEditing(_ notification: NSNotification)' I read the documentation, but I still don't know how to use it, Could you write a sample code for me? – Albert Tesla Ye Nov 22 '15 at 15:23
  • 1. I don't know what your comment means, but it's different from the code in the question. 2. In order to receive notifications, you must register for notifications. – nhgrif Nov 22 '15 at 15:24
0

Don't forget to set the delegate to where the data is (usually to self). i.e. wordTextfield = self (in ViewDidLoad)