Daniel Higgott
Daniel Higgott

Reputation: 51

How to override Copy and Paste NSMenuItems for one View Controller Swift macOS

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

Upvotes: 0

Views: 311

Answers (0)

Related Questions