NSTextField: exposing its Copy and Paste methods

北城以北 提交于 2019-12-17 20:55:52

问题


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.


回答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 filed has a cell as a child connected too it. (ps not programmer. Ill call it child)

The cell has a method for implementing a custom field editor called fieldeditorforview

class cell: NSTextFieldCell {

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

this function allows you to insert your own custom nstextview

here is my custom nstextview

class ESPasteView: NSTextView, NSTextViewDelegate {

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
    }

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

}

sorry its in swift. but i have it working in my own application. Had to modify though. Should work.

credit to:

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

and Ken Thomases who pointed out the field editor




回答2:


Maybe you could take a look at NSTextField's:

- (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard type:(NSString *)type;
- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type;

This would allow you to intercept the call customize the response.



来源:https://stackoverflow.com/questions/15748945/nstextfield-exposing-its-copy-and-paste-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!