0

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?

Ced
  • 93
  • 8
  • [NSControlDelegateMethods](https://developer.apple.com/reference/appkit/nscontrol#//apple_ref/occ/instm/NSObject/controlTextDidChange:) – NSNoob Apr 12 '17 at 13:55

1 Answers1

3

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571