How to handle NSTextField change in macOS

Issue #438

Storyboard

In Storyboard, NSTextField has an Action option that specify whether Send onSend on Enter only` should be the default behaviour.

textfield

Code

In code, NSTextFieldDelegate notifies whenever text field value changes, and target action notifies when Enter key is pressed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate {

@IBOutlet weak var textField: NSTextField!

override func viewDidLoad() {
super.viewDidLoad()

textField.delegate = self
}

func controlTextDidChange(_ obj: Notification) {
let textField = obj.object as! NSTextField
print(textField.stringValue)
}
}

Use EasyClosure

If we use EasyClosure then this is easy

1
2
3
4
5
6
7
8
9
let textField: NSTextField = 

textField.on.action { string in
print("User has pressed enter \(string)"
}

textField.on.change { string in
print("Text field value has changed")
}

Updated at 2020-11-27 07:39:43

Comments