UIMenuController 聊天时的复制、删除、撤回
2016-11-08 本文已影响360人
汪小喵
![Uploading 屏幕快照 2016-11-08 下午12.35.00_719577.png . . .]
屏幕快照 2016-11-08 下午12.35.00.png
喏,就是这个小东西,聊天的时候我们都用到了,实际开发中好像不太常用。它叫做UIMenuController,下面分享它的使用。
一般是在长按的时候会出现这个小菜单,那么就需要在长安出现菜单的控件上加一个手势:
[view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]];
让后我们来实现这个longPress:方法:
- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer {
if (longRecognizer.state == UIGestureRecognizerStateBegan) {
[view becomeFirstResponder];
UIMenuController *menu = [UIMenuController sharedMenuController];
UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyItemClicked:)];
UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteItemClicked:)];
[menu setMenuItems:[NSArray arrayWithObjects:copyItem, deleteItem, nil]];
CGRect rect = view.bounds;
rect.origin.y = rect.origin.y - SCALE6P(10);
rect.size.height = rect.size.height + SCALE6P(20);
[menu setTargetRect:rect inView:view];
[menu setMenuVisible:YES animated:YES];
}
}
写好这些以后,长按那个 view ,UIMenuController并没有出现!还要加点几行。
#pragma mark 处理action事件
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == @selector(copyItemClicked:)) {
return YES;
} else if (action == @selector(deleteItemClicked:)){
return YES;
}
return [super canPerformAction:action withSender:sender];
}
#pragma mark 实现成为第一响应者方法
- (BOOL)canBecomeFirstResponder {
return YES;
}
让添加了UIMenuController的view响应才可以出现那个小黑框,但是点击复制和删除当然就没什么作用了。要实现@selector(copyItemClicked:)和@selector(deleteItemClicked:)方法才行啊!
- (void)deleteItemClicked:(id)sender {
NSLog(@"删除");
// 做删除,一般是tableView中删除某一行,不要忘记删除数据源在reload data 就好了。
NSIndexPath *indexPath ; // 计算你的tableView的indexPath
[self.list removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)copyItemClicked:(id)sender {
NSLog(@"复制");
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = youView.text;
}
OK,现在复制、删除的功能基本实现了。你可以在自己的工程中试试了。