UIMenuController使用

作者: lancely | 来源:发表于2016-04-24 15:54 被阅读233次
    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;
    }
    

    注意

    • 显示UIMenuController前必须调用becomeFirstResponder
    • 必须重写canBecomeFirstResponder方法返回YES
    • 有些控件会有系统的UIMenuItem,使用canPerformAction:withSender:方法筛选出需要的item

    相关文章

      网友评论

        本文标题:UIMenuController使用

        本文链接:https://www.haomeiwen.com/subject/rxefrttx.html