UIMenuController with custom item not working with UICollectionview

前端 未结 6 1012
长情又很酷
长情又很酷 2021-01-13 02:15

I have added custom menu controller when long press on UICollectionViewCell

    [self becomeFirstResponder];
    UIMenuItem *menuItem = [[UIMenuItem alloc] i         


        
6条回答
  •  臣服心动
    2021-01-13 02:27

    Maybe a bit late but i maybe found a better solution for those who are still search for this:

    In viewDidLoad of your UICollectionViewController add your item:

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

    Add the following delegate methods:

    //This method is called instead of canPerformAction for each action (copy, cut and paste too)
    - (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
            if (action == @selector(action:)) {
                return YES;
            }
            return NO;
        }
        //Yes for showing menu in general
        - (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
            return YES;
        }
    

    Subclass UICollectionViewCell if you didn't already. Add the method you specified for your item:

    - (void)action:(UIMenuController*)menuController {
    
    }
    

    This way you don't need any becomeFirstResponder or other methods. You have all actions in one place and you can easily handle different cells if you call a general method with the cell itself as a parameter.

    Edit: Somehow the uicollectionview needs the existence of this method (this method isn't called for your custom action, i think the uicollectionview just checks for existance)

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

提交回复
热议问题