不知你有沒有發現,在你的微信朋友中,長按一段文字(正文或者評論),會彈出這樣子的玩意:
這玩意很眼熟是吧?沒錯,你經常見到它,在很多iOS系統應用中,你想複製一段文字到另一處粘貼,你只要長按一下,這玩意就出來了。既然iOS自家的app中都有這個,那麼它一定有封裝的控件吧,以前我不知道他到底叫什麼,後來公司的項目中要用到這玩意了,當時打算自己實現,還叫設計MM切了圖,囧,但是在百度上谷歌了一番後,發現這個玩意在UIKit庫裏原來叫UIMenuController!廢話不多說了,讓我們來看看這個東西怎麼用的吧!先讓我們來看一下效果,我想在一段文字上長按就會彈出這個小東西:
要想在你的view或者viewController中實現長按彈出菜單欄你必須要調用becomeFirstResponder方法,其次要實現canBecomeFirstResponder方法,並返回YES.
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
//設置label的userInteractionEnabeld屬性爲YES
_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];
}
}
//處理item點擊事件
- (void)copyItemClicked:(UIMenuItem *)item
{
NSLog(@"複製");
}
- (void)collectItemClicked:(UIMenuItem *)item
{
NSLog(@"收藏");
}
- (void)reportItemClicked:(UIMenuItem *)item
{
NSLog(@"舉報");
}
//- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
//{
// if (action == @selector(copyItemClicked:)) {
// return YES;
// }else if(action == @selector(resendItemClicked:))
// {
// return YES;
// }
//
// return [super canPerformAction:action withSender:sender];
//
//}
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end