您的位置:首页 > 产品设计 > UI/UE

UIMenuController使用

2016-03-22 16:22 489 查看

定制菜单项

如果你想使用定制菜单项,下面代码比较隐晦,但非常灵活。你需要检测是否用户长按并显示菜单,而最简单的方法就是在表格单元格中使用
UILongPressGestureRecognizer


UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[cell addGestureRecognizer:recognizer];


为了让菜单显示,目标视图必须在 responder 链中,很多 UIKit 视图默认并无法成为一个 responder ,因此你需要之类这些视图重载 canBecomeFirstResponder 方法范围 YES





在下面例子中,我们使用定制类 TSTableViewCell 并实现了长按选择器

- (void)longPress:(UILongPressGestureRecognizer *)recognizer {

if (recognizer.state == UIGestureRecognizerStateBegan) {

TSTableViewCell *cell = (TSTableViewCell *)recognizer.view;

[cell becomeFirstResponder];

UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"Flag"action:@selector(flag:)];

UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"Approve"action:@selector(approve:)];

UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:@"Deny"action:@selector(deny:)];

UIMenuController *menu = [UIMenuController sharedMenuController];

[menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];

[menu setTargetRect:cell.frame inView:cell.superview];

[menu setMenuVisible:YES animated:YES];
}
}

- (void)flag:(id)sender {
NSLog(@"Cell was flagged");
}

- (void)approve:(id)sender {
NSLog(@"Cell was approved");
}

- (void)deny:(id)sender {
NSLog(@"Cell was denied");
}


There is only one small gotcha with
UIMenuItem
: if the specified action is not implemented by your view controller, that item will not appear in the menu.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: