Search code examples
swiftmacoscocoanstextfield

Deselect the text in a NSTextField


Is there an easy way to deselect an NSTextField after pressing enter?


Solution

  • First you will need to make your view controller the delegate of your text field. Then you override NSControl instance method controlTextDidEndEditing(_:), get your textfield current editor selected range and from the main thread set it back to your textfield:

    import Cocoa
    
    class ViewController: NSViewController, NSTextFieldDelegate {
        @IBOutlet weak var textField: NSTextField!
        override func viewDidLoad() {
            super.viewDidLoad()
            textField.delegate = self
        }
        override func controlTextDidEndEditing(_ obj: Notification) {
            if let selectedRange = textField.currentEditor()?.selectedRange {
                DispatchQueue.main.async {
                    self.textField.currentEditor()?.selectedRange = selectedRange
                }
            }
        }
    }