這里我們要實現的將是選擇按鈕的自定義
綜合上一節的隨筆,這里給出效果圖。
ViewController.m
// // ViewController.m // CX-MenuController // // Created by ma c on 16/4/7. // Copyright © 2016年 xubaoaichiyu. All rights reserved. // #import "ViewController.h" #import "CXLabel.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIWebView *webView; @property (weak, nonatomic) IBOutlet CXLabel *label; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.webView loadHTMLString:@"<div>旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚旭寶愛吃魚</.div>" baseURL:nil]; UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(click)]; [self.label addGestureRecognizer:longPress]; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; } - (void)click{ //讓自己成為第一響應者 [self.label becomeFirstResponder]; //初始化menu UIMenuController * menu = [UIMenuController sharedMenuController]; UIMenuItem * xu = [[UIMenuItem alloc]initWithTitle:@"旭" action:@selector(xu)]; UIMenuItem * bao = [[UIMenuItem alloc]initWithTitle:@"寶" action:@selector(bao)]; UIMenuItem * ai = [[UIMenuItem alloc]initWithTitle:@"愛" action:@selector(ai)]; UIMenuItem * chi = [[UIMenuItem alloc]initWithTitle:@"吃" action:@selector(chi)]; UIMenuItem * yu = [[UIMenuItem alloc]initWithTitle:@"魚" action:@selector(yu)]; menu.menuItems = @[xu,bao,ai,chi,yu]; //設置menu的顯示位置 [menu setTargetRect:self.label.frame inView:self.view]; //讓menu顯示並且伴有動畫 [menu setMenuVisible:YES animated:YES]; } - (void)xu{ } - (void)bao{ } -(void)ai{ } -(void)chi{ } -(void)yu{ } @end
CXLabel.m
// // CXLabel.m // CX-MenuController // // Created by ma c on 16/4/7. // Copyright © 2016年 xubaoaichiyu. All rights reserved. // #import "CXLabel.h" @implementation CXLabel - (void)awakeFromNib{ [self setup]; } -(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self setup]; } return self; } - (void)setup{ //允許用戶交互 self.userInteractionEnabled = YES; } //允許自己成為第一響應者 - (BOOL)canBecomeFirstResponder{ return YES; } //Label能夠執行哪些操作(menu) - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{ // if (action == @selector(copy:) || action == @selector(cut:) || action == @selector(paste:)) { // return YES; // } return NO; } - (void)copy:(id)sender{ //復制版 UIPasteboard * paste = [UIPasteboard generalPasteboard]; paste.string = self.text; } - (void)cut:(id)sender{ UIPasteboard * paste = [UIPasteboard generalPasteboard]; paste.string = self.text; self.text = nil; } - (void)paste:(id)sender{ UIPasteboard * paste = [UIPasteboard generalPasteboard]; self.text = paste.string; } @end