Displaying menu on longpress on UIView in UITableViewCell

823 views Asked by At

In an IOS app, I want to display a UIMenuController when longpressing an UIView located in UITableViewCell.

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    myTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell==nil)
    {
        cell=(myTableViewCell*)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    myView=<initMyView>
    [cell.contentView addSubview:myView];
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapGestureCapturedOnView:)];
    longTap.minimumPressDuration=0.5f;
    [myView addGestureRecognizer:longTap];

    return cell;
}

- (void)longTapGestureCapturedOnView:(UITapGestureRecognizer *)gesture
{
    items=[[NSMutableArray alloc]init];
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        [items addObject:[[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(myCopy:)]];
        [items addObject:[[UIMenuItem alloc] initWithTitle:@"Custom" action:@selector(myCustom:)]];
    }

    [[UIMenuController sharedMenuController] setMenuItems:items];
    [[UIMenuController sharedMenuController] update];
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL result = NO;
    if(@selector(myCopy:) == action ||@selector(myCustom:) == action ) {
        result = YES;
    }
    return result;
}

The longTapGestureCapturedOnView is called, as well as the canPerformAction which is returning YES in the 2 cases, but no menuitem appears on the screen. What could I have done wrong ?

1

There are 1 answers

0
Shehata Gamal On

You also need

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
   return YES ;
}

//

also it's not right to add gestures in cellForRowAt as it's being called upon scroll & cellReusing so add it in awakeFormNib method of UITableViewCell custom class