swiftmacosnscontrol

How to catch some events on a NSControl in swift


I am writing an application for OSX in Swift and I am looking for a good way to catch events on a NSControl. Obviously, I searched but the informations I found are often unclear or old. In my case, I would like to catch several events on a NSTextField (key up, text changed, focus lost,...).

When I push on “Enter” in the NSTextField, it sends an action. Maybe is there a way to send an action when I click or write in the NSTextField?


Solution

  • You can subclass NSTextField and override textDidChange for text change, textDidEndEditing for lost focus and keyUp method for key up. Try like this:

    import Cocoa
    
    class CustomTextField: NSTextField {
        override func viewWillMove(toSuperview newSuperview: NSView?) {
            // customize your field here
            frame = newSuperview?.frame.insetBy(dx: 50, dy: 50) ?? frame
        }
        override func textDidChange(_ notification: Notification) {
            Swift.print("textDidChange")
        }
        override func textDidEndEditing(_ notification: Notification) {
            Swift.print("textDidEndEditing")
        }
        override func keyUp(with event: NSEvent) {
            Swift.print("keyUp")
        }
    }
    

    View Controller sample Usage:


    import Cocoa
    class ViewController: NSViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            let textField = CustomTextField()
            view.addSubview(textField)
        }
    }
    

    Sample