
image.png
關(guān)于UIMenuController
UIMenuController單例是由系統(tǒng)管理觸碰隱藏邏輯的控件,特別在UITableView中cell需要這樣的彈窗效果,顯示隱藏等邏輯操作,為開(kāi)發(fā)者省去很多時(shí)間。
使用直接上代碼:
//
// 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:@"這是個(gè)按鈕" 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]; //此代碼比較重要,當(dāng)自定義view的時(shí)候,會(huì)導(dǎo)致item出不來(lái)
UIMenuItem *item0 = [[UIMenuItem alloc]initWithTitle:@"復(fù)制" 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];
}
}
// 是否能成為第一響應(yīng)者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
// 用于UIMenuController顯示,缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(copyAction)
|| action ==@selector(deletedAction)){
return YES;
}
return NO;//隱藏系統(tǒng)默認(rèn)的菜單項(xiàng)
}
- (void)copyAction
{
NSLog(@"%s 第%d行",__FUNCTION__,__LINE__);
}
- (void)deletedAction
{
NSLog(@"%s 第%d行",__FUNCTION__,__LINE__);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
注意的點(diǎn)在于
一、是否能成為第一響應(yīng)者
// 是否能成為第一響應(yīng)者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
二、隱藏系統(tǒng)默認(rèn)的菜單項(xiàng) & 顯示自定義菜單
// 用于UIMenuController顯示,缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if (action == @selector(copyAction)
|| action ==@selector(deletedAction)){
return YES;
}
return NO;//隱藏系統(tǒng)默認(rèn)的菜單項(xiàng)
}
三、成為第一響應(yīng)者

image.png