在iOS開發(fā)中,我們可能有需求需要長按某個控件來復制內(nèi)容手素。
第一種情況鸳址,直接使用tableview的方法來調(diào)用系統(tǒng)的復制剪切那個功能。
// 允許 Menu 菜單
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row !=0) {
return YES;
}
return NO;
}
// 每個 Cell都會出現(xiàn) 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];
}
}
第二種是自定義(這里主要是改掉系統(tǒng)拷貝的名字為復制)
//在自定義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;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者