NSTextField: exposing its Copy and Paste methods

I am trying to access the copy, cut, and paste methods of a NSTextField instance in its window delegate so I can customize these methods. I find that unlike tableViews and textViews, the textfield's copy, paste and cut actions are not responsive in the delegate. My understanding is that all text controls share the window's field editor yet this does not seem to be the case.

I thought perhaps the TextField's field editor was not being shared with the window delegate, however I did some testing I see that as I am typing in control, those field editors are identical--very strange.

My current work-around is to use a subclass instance of NSTextView where the copy and paste action methods respond as needed. This, however, has its own issues and I was hoping there was some way to get NSTextFields to work as expected.


Solution 1:

A nstextfield does not have copy and paste functions. Those are only found in nstextview. the catch is that when a textfield is edited it opens up a textview called a fieldeditor during the editing and sets that as the first responder.

How to solve:

Each text field has a cell as a child connected to it (called cell in the picture but should be named more appropriately, e.g. CustomTextEditor):

enter image description here

The cell has a method for implementing a custom field editor called fieldEditorForView:

class cell: NSTextFieldCell {

    var editor: NSTextView

    override func fieldEditorForView(aControlView: NSView) -> NSTextView? {
        if editor == nil {
            editor = ESPasteView()
        }
        return editor
    }

}

This above function allows you to provide your own custom NSTextView subclass:

class ESPasteView: NSTextView, NSTextViewDelegate {

    override func paste(sender: AnyObject?) {
        Swift.print("user tries to paste")
        super.pasteAsPlainText(nil)
    }

}

Credit to:

How to disable context menus with right mouse click in an NSTextField (Cocoa)?

and Ken Thomases who pointed out the field editor.