• iOS中UIMenuController的使用


    不知你有没有发现,在你的微信朋友中,长按一段文字(正文或者评论),会弹出这样子的玩意:

    这里写图片描述

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

    #import "ViewController.h"

     

    @interface ViewController ()

     

    @property(nonatomic,strong)UILabel *label;

    @end

     

    @implementation ViewController

     

    - (void)viewDidLoad {

        [super viewDidLoad];

        

        _label = [[UILabel alloc]initWithFrame:CGRectMake(60, 100, 200, 50)];

        _label.text = @"我是一个label";

        _label.textAlignment = NSTextAlignmentCenter;

        _label.textColor = [UIColor blackColor];

        [self.view addSubview:_label];

        

        self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

        //

        _label.userInteractionEnabled = YES;

        //添加长按手势

        [_label addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]];

    }

     

    -(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;

    }

     

     

    - (void)didReceiveMemoryWarning {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

     

    @end

  • 相关阅读:
    07 MySQL之视图
    05 MySQL之查询、插入、更新与删除
    04 MySQL之函数
    02 MySQL之数据表的基本操作
    03 MySQL之数据类型和运算符
    Django之通用视图
    01 MySQL之数据库基本操作
    Elasticsearch-Head基本使用方法
    PinPoint使用手册(转)
    rest-assured学习资料
  • 原文地址:https://www.cnblogs.com/linxiu-0925/p/4982232.html
Copyright © 2020-2023  润新知