UICollectionView Custom Actions and UIMenuController

The UICollectionView can provide a special UIMenuController with cut, copy, and paste actions. To add UICollectionView custom actions you need to implement a few extra methods for the shared UIMenuController object. The view controller's parent window needs to be the key window and you'll need to respond to UIResponder method canBecomeFirstResponder. In your UICollectionViewController class do the following:

[objc] // ViewController.h @interface ViewController : UICollectionViewController

// ViewController.m -(void)viewDidLoad { [super viewDidLoad]; self.collectionView.delegate = self;

UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Custom Action" action:@selector(customAction:)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];


#pragma mark - UICollectionViewDelegate methods - (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { return YES; // YES for the Cut, copy, paste actions }

- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath { return YES; }

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { NSLog(@"performAction"); }

#pragma mark - UIMenuController required methods - (BOOL)canBecomeFirstResponder { // NOTE: This menu item will not show if this is not YES! return YES; }

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { NSLog(@"canPerformAction"); // The selector(s) should match your UIMenuItem selector if (action == @selector(customAction:)) { return YES; } return NO; }

#pragma mark - Custom Action(s) - (void)customAction:(id)sender { NSLog(@"custom action! %@", sender); } [/objc]

Here's what it looks like:

UIMenuController Custom UICollectionView