您的当前位置:首页正文

iOS开发使用系统的拷贝剪切功能

2024-12-06 来源:伴沃教育

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

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

-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath

{

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

return YES;

}

return NO;

}

-(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:)) {

UsermessageCell *messageCell = (UsermessageCell *)[tableView cellForRowAtIndexPath:indexPath];

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

}

}

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

//在自定义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;

}
显示全文