如果是用 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:
但如果要設定自己的 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!");
}

沒有留言:
張貼留言