iOS開發長按tabbaleVew

weixin_34402408發表於2016-06-27

實現步驟:
1.給cell新增UILongPressGestureRecognizer和相應處理事件

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    ..............
    UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:selfaction:@selector(cellLongPress:)];
    [cell addGestureRecognizer:longPressGesture];
    return cell;
    }
    2.配置和顯示UIMenuController

  • (void)cellLongPress:(UIGestureRecognizer *)recognizer{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
    CGPoint location = [recognizer locationInView:self];
    NSIndexPath * indexPath = [self indexPathForRowAtPoint:location];
    UIMyTableViewCell *cell = (UIMyTableViewCell *)recognizer.view;
         //這裡把cell做為第一響應(cell預設是無法成為responder,需要重寫canBecomeFirstResponder方法)
    [cell becomeFirstResponder];

      UIMenuItem *itCopy = [[UIMenuItem alloc] initWithTitle:@"複製" action:@selector(handleCopyCell:)];
      UIMenuItem *itDelete = [[UIMenuItem alloc] initWithTitle:@"刪除" action:@selector(handleDeleteCell:)];        
      UIMenuController *menu = [UIMenuController sharedMenuController];
    

[menu setMenuItems:[NSArray arrayWithObjects:itCopy, itDelete, nil]];
[menu setTargetRect:cell.frame inView:self];
[menu setMenuVisible:YES animated:YES];

    [itCopy release];
    [itDelete release];
}

}

  • (void)handleCopyCell:(id)sender{//複製cell
    NSLog(@"handle copy cell");
    }

  • (void)handleDeleteCell:(id)sender{//刪除cell
    NSLog(@"handle delete cell");
    }

3.在自定義的cell裡重寫canBecomeFirstResponder方法,返回yes
//為了讓選單顯示,目標檢視必須在responder鏈中,很多UIKit檢視預設並無法成為一個responder,因此你需要使這些檢視過載 canBecomeFirstResponder方法,並返回YES

  • (BOOL)canBecomeFirstResponder{
    return YES;
    }

經過這幾步,就可以成功顯示了,又在網上看到一篇講這個的外文,分享一下:
http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller

相關文章