UIMenuController使用 /模拟朋友圈收藏/复制弹窗

UIMenuController使用 /模拟朋友圈收藏/复制弹窗_第1张图片
image.png
关于UIMenuController

UIMenuController单例是由系统管理触碰隐藏逻辑的控件,特别在UITableView中cell需要这样的弹窗效果,显示隐藏等逻辑操作,为开发者省去很多时间。

使用直接上代码:
//
//  ViewController.m
//  UIMenuControllerDemo
//
//  Created by Grabin on 2017/11/25.
//  Copyright © 2017年 GrabinWong. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIButton *abtn;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
}

- (void)setUpUI
{
    _abtn = [[UIButton alloc] initWithFrame:CGRectMake(55.0, 80.0, 220.0, 40.0)];
    [_abtn setTitle:@"这是个按钮" forState:UIControlStateNormal];
    [_abtn setBackgroundColor:[UIColor orangeColor]];
    [_abtn addTarget:self action:@selector(clickBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_abtn];
}

- (void)clickBtnAction:(UIButton *)abtn
{
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (menuController.isMenuVisible) {
        [menuController setMenuVisible:NO animated:YES];
    } else {
        [self becomeFirstResponder]; //此代码比较重要,当自定义view的时候,会导致item出不来
        UIMenuItem *item0 = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copyAction)];
        UIMenuItem *item1 = [[UIMenuItem alloc]initWithTitle:@"删除" action:@selector(deletedAction)];
        menuController.menuItems = @[item0,item1];
        menuController.arrowDirection = UIMenuControllerArrowUp;
        [menuController setTargetRect:abtn.frame inView:self.view];
        [menuController setMenuVisible:YES animated:YES];
    }
}

// 是否能成为第一响应者
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

// 用于UIMenuController显示,缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if (action == @selector(copyAction)
        || action ==@selector(deletedAction)){
        return YES;
    }
    return NO;//隐藏系统默认的菜单项
}

- (void)copyAction
{
    NSLog(@"%s 第%d行",__FUNCTION__,__LINE__);
}

- (void)deletedAction
{
    NSLog(@"%s 第%d行",__FUNCTION__,__LINE__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end

注意的点在于

一、是否能成为第一响应者
// 是否能成为第一响应者
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
二、隐藏系统默认的菜单项 & 显示自定义菜单
// 用于UIMenuController显示,缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if (action == @selector(copyAction)
        || action ==@selector(deletedAction)){
        return YES;
    }
    return NO;//隐藏系统默认的菜单项
}
三、成为第一响应者
UIMenuController使用 /模拟朋友圈收藏/复制弹窗_第2张图片
image.png

你可能感兴趣的:(UIMenuController使用 /模拟朋友圈收藏/复制弹窗)