iOS 长按出现复制、剪切、粘贴标签

在iOS开发中,我们可能有需求需要长按某个控件来复制内容。

第一种情况,直接使用tableview的方法来调用系统的复制剪切那个功能。

// 允许 Menu 菜单
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.section == 0 && indexPath.row !=0) {

        return YES;

    }

    return NO;

}
// 每个 Cell都会出现 Menu 菜单
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender

{

    if (action == @selector(copy:)) {

        return YES;

    }

    return NO;

}

// 拷贝、剪切、粘贴按钮的操作定义
-(void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender

{

   if(action == @selector(copy:)) {
      [UIPasteboard generalPasteboard].string = [self.array objectAtIndex:indexPath.row];
  }
  if(action == @selector(cut:)) {
    [UIPasteboard generalPasteboard].string = [self.array objectAtIndex:indexPath.row];
    [self.array replaceObjectAtIndex:indexPath.row withObject:@""];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
  }
  if(action == @selector(paste:)) {
     NSString *pasteString = [UIPasteboard generalPasteboard].string;
     NSString *tempString = [NSString stringWithFormat:@"%@%@",[self.array objectAtIndex:indexPath.row],pasteString];
     [self.array replaceObjectAtIndex:indexPath.row withObject:tempString];
     [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
  }
}

第二种是自定义(这里主要是改掉系统拷贝的名字为复制)


//在自定义cell中的init方法加入
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressCellHandle:)];

self.longGesture = longPressGesture;

[self addGestureRecognizer:longPressGesture];

//并加上几个方法

-(void)longPressCellHandle:(UILongPressGestureRecognizer *)gesture

{

[self becomeFirstResponder];

UIMenuController *menuController = [UIMenuController sharedMenuController];

UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(menuCopyBtnPressed:)];

menuController.menuItems = @[copyItem];

[menuController setTargetRect:gesture.view.frame inView:gesture.view.superview];

[menuController setMenuVisible:YES animated:YES];

[UIMenuController sharedMenuController].menuItems=nil;

}

-(void)menuCopyBtnPressed:(UIMenuItem *)menuItem

{

[UIPasteboard generalPasteboard].string = self.messageLab.text;

}

-(BOOL)canBecomeFirstResponder

{

return YES;

}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender

{

if (action == @selector(menuCopyBtnPressed:)) {

return YES;

}

return NO;

}

你可能感兴趣的:(iOS 长按出现复制、剪切、粘贴标签)