iOS点点滴滴iOS开发专题

UIMenuController使用

2016-04-24  本文已影响233人  lancely
UIMenuController演示

要想在你的view或者viewController中实现长按弹出菜单栏你必须要调用becomeFirstResponder方法,其次要实现canBecomeFirstResponder方法,并返回YES.

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong)UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    _label = [[UILabel alloc]initWithFrame:CGRectMake(60, 100, 200, 50)];
    _label.text = @"我是一个label";
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor blackColor];
    _label.userInteractionEnabled = YES;
    //添加长按手势
    [_label addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]];
    [self.view addSubview:_label];
}

-(void)longPress:(UILongPressGestureRecognizer *)sender{
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self.view becomeFirstResponder];
        _label.backgroundColor = [UIColor lightGrayColor];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        //复制
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyItemClicked:)];
        //收藏
        UIMenuItem *collectItem = [[UIMenuItem alloc] initWithTitle:@"收藏" action:@selector(collectItemClicked:)];
        //举报
        UIMenuItem *reportItem = [[UIMenuItem alloc] initWithTitle:@"举报" action:@selector(reportItemClicked:)];
        menu.menuItems = @[copyItem,collectItem,reportItem];
        [menu setMenuVisible:YES animated:YES];
        [menu setTargetRect:_label.frame inView:self.view];
    }
    if (sender.state==UIGestureRecognizerStateEnded) {
        _label.backgroundColor = [UIColor clearColor];
    }
}

- (void)copyItemClicked:(UIMenuItem *)item{
    NSLog(@"复制");
}

- (void)collectItemClicked:(UIMenuItem *)item{
    NSLog(@"收藏");
}

- (void)reportItemClicked:(UIMenuItem *)item{
    NSLog(@"举报");
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}

// 有些控件会有系统的UIMenuItem,使用此方法筛选
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
  /*
  if (action == @selector(xxxxx)) {
    return YES;
  }
  return NO;
  */
  return YES;
}

注意

上一篇下一篇

猜你喜欢

热点阅读