概念:
UIMenuController即菜单控制器,是一个单例对象,用来复制,粘贴,删除等内容的操作。
1、实例:WKWebView或UITextView
调用方法addSelectedContentView:即可
#pragma mark -- UIMenuController,(UIMenuController即菜单控制器,是一个单例对象,用来复制,粘贴,删除等内容的操作)
- (void)addSelectedContentView:(UIview*)view {
// 给WKWebView添加UIMenuItem
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setTargetRect:self.view.frame inView:self.view];
// 添加两个新的菜单:翻译、7500查询
UIMenuItem *translateItem = [[UIMenuItem alloc] initWithTitle:@"翻译" action:@selector(translateSelected:)];
UIMenuItem *shiyiItem = [[UIMenuItem alloc] initWithTitle:@"释义" action:@selector(shiYiSelected:)];
// 自定义菜单添加到菜单栏中
// [menu setMenuItems:@[translateItem, shiyiItem]];
menu.menuItems = @[translateItem, shiyiItem];
menu.menuVisible = YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
// 该方法与编辑菜单相关,与返回YES的方法关联的菜单将显示出来。
if (action == @selector(translateSelected:) || action == @selector(shiYiSelected:)) {
return YES;
} else {
return NO;
}
}
- (void)translateSelected:(id)sender {
// 翻译取词
// 获取选择的文本
/// 1、这是在UITextView上,选取文本
/// NSString *selectString = [self.textView.text substringWithRange:self.textView.selectedRange];
/// self.textView.selectedRange= NSMakeRange(0, 0); // 清除选中的内容
/// 2、这是在WKWebView上,选取文本
NSString *jsCript = @"window.getSelection().toString()";
[self.webView evaluateJavaScript:jsCript completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@", result); // 选中的文本:result
}];
}
2、实例:UILabel:这里是写在UILabel的分类中(不常用可以随意添加手势)
原理:给UILabel添加长按手势,
#import "UILabel+WLCopy.h"
@implementation UILabel (WLCopy)
// 初始化设置长按操作
- (void)pressAction {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
longPress.minimumPressDuration = 1;
[self addGestureRecognizer:longPress];
}
- (void)longPressAction:(UIGestureRecognizer *)recognizer {
[self becomeFirstResponder];
UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"拷贝" action:@selector(customCopy:)];
UIMenuItem *soundItem = [[UIMenuItem alloc] initWithTitle:@"句段发音" action:@selector(customSound:)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyItem,soundItem, nil]];
[[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}
// 使label能够成为响应事件
- (BOOL)canBecomeFirstResponder {
return YES;
}
// 控制响应的方法
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if(action == @selector(customCopy:))
{
return YES;
}else if(action == @selector(customSound:))
{
return YES;
}
return NO;
}
- (void)customCopy:(id)sender {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = self.text;
}
- (void)customSound:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"SentenceSoundNotification" object:[NSString stringWithFormat:@"%@",self.text]];
}
@end