Search code examples
iosuicollectionviewkeyboard-shortcutsuikeycommand

How to implement support for copy keyboard shortcut in UICollectionViewCell?


If you implement override func copy(_ sender: Any?) {} in a view controller, present that view controller, then hold down command the keyboard shortcuts overlay appears revealing Copy is an available action. But if you do that in a collection view cell then focus on one of those cells (highlight it via arrow keys) and hold command, copy is not listed. In iPadOS 15, the responder chain starts at the focused view, so I thought this would work.

If you implement override func printContent(_ sender: Any?) { } in the cell (and add the key to the info.plist to indicate print is supported), then Print is listed as an available keyboard shortcut when the cell is focused. This is super similar to copy so I’m confused why works for print but not copy.

Is there something more I need to do to support copy in cells?


Solution

  • I filed a bug report and Apple replied with the following information:

    cut:, copy: and paste: are methods that are handled directly by collection view via the delegate method collectionView:canPerformAction:forItemAtIndexPath:withSender:. If you don't implement this method, or if you implement context menus, which supersede this method, then cells return NO from canPerformAction:withSender: for these methods.

    If you want to implement these methods yourself on the cell, then you can also override canPerformAction:withSender: and return YES, indicating that you handle this action yourself.

    I was able to get this working as expected by adding the following to my cell subclass:

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        switch action {
        case #selector(copy(_:)):
            return true
        default:
            return super.canPerformAction(action, withSender: sender)
        }
    }
    
    override func copy(_ sender: Any?) {
        print("Cell wants to copy")
    }