Albert Tesla Ye
Albert Tesla Ye

Reputation: 43

How to use DidEndEditing on textfield on OS X (swift)

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")
    }
}

Upvotes: 0

Views: 1229

Answers (3)

Phillip Brisco
Phillip Brisco

Reputation: 11

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

Upvotes: 0

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

    }
}

Upvotes: 1

nhgrif
nhgrif

Reputation: 62062

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.

Upvotes: 0

Related Questions