Sean's Note: [iOS8] How to show menu(Cut, Copy, Paste or custom action) when long pressing the cell of UITableView?

2014年11月18日 星期二

[iOS8] How to show menu(Cut, Copy, Paste or custom action) when long pressing the cell of UITableView?

如果是用 UITableViewCell,只需要 override 三個方法:

//
// CustomUITableView.m
//

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

//
// CustomUITableView.m
//

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

-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return YES;
}

//  Need to override even perform nothing.
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    if (action == @selector(copy:)) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
        [pasteBoard setString:cell.textLabel.text];
    }
}

長按 cell 後就會跳出 Cut, Copy 和 Paste:

圖1. UIMenuController

但如果要設定自己的 menu item 如果不 subclass UITableCellView,長按 cell 也只會跳出 

Cut, Copy 和 Paste,不會看到自己透過 setMenuItems 所加入的 UIMenuItem。

這時就需要 subclass UITableCellView:

//
// CustomUITableView.m
//

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"Test" action:@selector(test:)];    
    [[UIMenuController sharedMenuController] setMenuItems: @[testMenuItem]];
    [[UIMenuController sharedMenuController] update];
}

//
// CustomUITableViewCell.m
//

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
     NSLog(@"CustomTableViewCell: %@\n", NSStringFromSelector(action));
    // There will be lots of default items if don't check.
    if (action == @selector(copy:) || action == @selector(test:))
        return YES;
    return NO;
}

// It's said need to be overrode from forums, but test ok without overriding it.
//-(BOOL)canBecomeFirstResponder {
//    return YES;
//}

/// this methods will be called for the cell menu items
-(void) test: (id) sender {
    NSLog(@"CustomTableViewCell: test!");
}

沒有留言:

張貼留言