2

I am having multiple textfields and I won't to invoke an action method if the user clicks on a textfield, this is what I currently have:

override func mouseDown(theEvent: NSEvent) {

}

for the click event.

This is the action to which it should reference when a textfield is pressed:

func myAction(sender: NSView)
{
    print("aktuell: \(sender)")
    currentObject = sender
}

For buttons it is working with the action and selector but this does not work for textfields...

button.action = #selector(myAction)

Please give examples only in swift, I know that there are plenty of examples in obj.-c. Thanks!

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

1 Answers1

0

Got it working with that:

1) Create a subclass of NSTextField.

import Cocoa

class MyTextField: NSTextField {

    override func mouseDown(theEvent:NSEvent) {
        let viewController:ViewController = ViewController()
        viewController.textFieldClicked()
    }
}

2) With Interface building, select the text field you want to have a focus on. Navigate to Custom Class on the right pane. Then set the class of the text field to the one you have just created.**

3) The following is an example for ViewController.

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func textFieldClicked() -> Void {
        print("You've clicked on me!")
    }
}
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
  • You should use target action inside of `mouseDown()`. This will call the appropriate method. Creating a new view controller is a very bad idea. – clemens Mar 09 '17 at 09:12