#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CellMenuController : UIViewController
@property(strong, nonatomic) NSMutableArray *dataSource;
@property(strong, nonatomic) UITableView *tableView;
@end
#import "CellMenuController.h"
@interface CellMenuController () <UITableViewDelegate, UITableViewDataSource>
@end
@implementation CellMenuController
- (id)init {
if (self = [super init]) {
self.dataSource = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", nil];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:_tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *Identifity = NSStringFromClass([CellMenuController class]);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifity];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifity];
}
cell.textLabel.text = self.dataSource[indexPath.row];
// 增加长按首饰
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
[cell addGestureRecognizer:longPress];
return cell;
}
- (void)longTap:(UILongPressGestureRecognizer *)longPressGestureRecognizer {
if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
[self becomeFirstResponder];
UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMenuItem)];
UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(repostMenuItem)];
UIMenuItem *item2 = [[UIMenuItem alloc] initWithTitle:@"收藏" action:@selector(collectMenuItem)];
UIMenuItem *item3 = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMenuItem)];
UIMenuController *menuController = [UIMenuController sharedMenuController];
menuController.menuItems = @[item, item1, item2, item3];
[menuController setTargetRect:self.view.bounds inView:self.view];
[menuController setMenuVisible:YES animated:YES];
}
}
// 此方法如果不实现,菜单则显示不出来
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void) copyMenuItem {
NSLog(@"复制");
}
- (void) repostMenuItem {
NSLog(@"转发");
}
- (void) collectMenuItem {
NSLog(@"收藏");
}
- (void) deleteMenuItem {
NSLog(@"删除");
}
@end
效果截屏: