0

I am writing a macOS application with multiple view controllers, using Storyboards.

In my main View Controller I would like to be able to copy and paste data to the NSPasteboard. The data is related to buttons displayed to the user, and the exact data to be copied varies depending on which button has most recently been pressed/selected.

I would like to be able to override the standard behaviour of the Copy and Paste NSMenuItems when my main View Controller is the front most (key) window, but revert to back to standard behaviour when other windows are in the foreground, as they all contain NSTextFields which can be copied/pasted into.

I have done a lot of googling, and overriding this behaviour is not very well documented. I can achieve it globally by adding an IBAction into the App Delegate, which I could use to call a function in whichever View Controller is key, but this doesn't feel like a very elegant solution.

Currently my IBAction in the App Delegate looks like this:

@IBAction func copy(_ sender: Any) {

    if let window = NSApplication.shared.keyWindow {
        if let splitView = window.contentViewController as? SplitViewController {
            if let controlVC = splitView.controlItem.viewController as? ControlViewController {
                controlVC.copyAction(self)
            }
        }
    }
}

Am I missing a neater solution?

Thanks,

Dan

  • Implement copy and paste in the view controller? – Willeke Feb 29 '20 at 23:07
  • Yes, so I have a view controller containing 16 buttons. When the user presses a button, that button is highlighted/selected. The user can then decide to copy some data to the Pasteboard. Currently there is a separate button within the view called Copy which is attached to an action that runs this code, but I would like the user to be able to select Copy from the Edit Menu, or press Command-C to copy the data, which is where I have become unstuck. – Daniel Higgott Mar 01 '20 at 18:41
  • Does this answer your question? [How do I access copy paste functionality in NSViewController](https://stackoverflow.com/questions/40612610/how-do-i-access-copy-paste-functionality-in-nsviewcontroller) – Willeke Mar 02 '20 at 07:55
  • Unfortunately not, if I add those IBActions, I can run my custom code, but I loose all the inbuilt Copy/Paste functionality in the rest of the app, in all NSTextFields etc. – Daniel Higgott Mar 02 '20 at 20:50
  • Did you change the menu items? – Willeke Mar 02 '20 at 22:30
  • No, I’m using the standard edit menu menu items. – Daniel Higgott Mar 03 '20 at 23:02
  • Are the text fields in another window? – Willeke Mar 03 '20 at 23:35
  • Yes, though the windows are presented as a Sheet – Daniel Higgott Mar 06 '20 at 16:08
  • I tried to reproduce the issue but i can't. Please post a [mre]. – Willeke Mar 06 '20 at 22:34

0 Answers0