一、使用UITableViewDelegate方法無需子類化
前提:我們假設一個控制器中有一個tableView,并完成了tableView的基本設置。
0.在viewDidLoad中:給menu添加一個舉報的Item
UIMenuItem *testMenuItem = [[UIMenuItem alloc] initWithTitle:@"舉報" action:@selector(report:)];
UIMenuController *menu=[UIMenuController sharedMenuController];
[menu setMenuItems: @[testMenuItem]];
[menu update];//必須要更新
1.是否顯示Menu
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
2.是否該顯示系統(tǒng)菜單選項并調(diào)(就是到底顯示系統(tǒng)的哪幾項)
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
//顯示一個系統(tǒng)的,一個自定義的
return (action == @selector(copy:) || action == @selector(report:));
}
3.根據(jù)action來判斷具體要什么執(zhí)行動作
-(void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
if (action == @selector(copy:)) {
NSLog(@"copy...");
}
else if(action == @selector(report:)){
NSLog(@"report...");
}
}
二、使用長按手勢加子類化(大多數(shù)用到cell都會把它子類化的)
0.在cell子類化初始化方法中或者在數(shù)據(jù)源方法返回cell的時候都可以加上手勢
UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
[cell addGestureRecognizer:longPress];
1.實現(xiàn)長按方法
-(void)longPress:(UILongPressGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateBegan) {
YDSonCommentCell *cell = (YDSonCommentCell *)recognizer.view;
[cell becomeFirstResponder];
UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"舉報"action:@selector(report:)];
UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"拷貝"action:@selector(copy:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:report,copy, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
}
}
2.cell子類化實現(xiàn)兩個方法
//只有成為第一響應者時menu才會彈出
-(BOOL)canBecomeFirstResponder
{
return YES;
}
//是否可以接收某些菜單的某些交互操作
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
return (action == @selector(copy:) || action == @selector(report:));
}
//實現(xiàn)這兩個方法來執(zhí)行具體操作
-(void)copy:(id)sender{
[UIPasteboard generalPasteboard].string=self.comment.Content;
}
-(void)report:(id)sender{
NSLog(@"舉報啦");
}
總結:第一種用起來比較簡便,適合沒有特殊要求的UIMenuController,由于一般使用cell都需要子類化,而且第二種更容易控制菜單控制器具體顯示的位置和方向以及一些其他屬性,比較靈活,看大家喜好了