Search code examples
swiftmacosnstextfieldspelling

Spelling in NSTextField with Swift


How can I check the spelling of a NSTextField using swift? I'm already using controlTextDidChange to validate the text. This solution seems to mention casting the first responder as a NSTextView but I'm not sure that is possible with swift using coercion. I know this would be easier if I changed to a NSTextView but if possible I'd like to avoid this.


Solution

  • This should help you out.

    // Focus TextField
    phraseTextField.becomeFirstResponder()
    // Enable Continous Spelling
    let textView: NSTextView = (self.window!.firstResponder as! NSTextView)
    textView.continuousSpellCheckingEnabled = true
    

    Adapted from: How do I enable spell checking within an NSTextField on Mac OS X?


    In other situations, it may just work better to change NSTextFields to NSTextViews. Simply use a "Text View" (search NSTextView in the Object Library) and spell check will be on by default. NSTextFields simply do not support spell check in some cases, as best I can tell.

    Also consult: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextView_Class/#//apple_ref/doc/uid/20000373-SW55