关于输入框的UIMenuController

屏幕快照 2017-05-19 下午5.05.29.png

####背景
项目中有个页面有一个自定义的textView输入框,其一用于四六级写作翻译的答题,其二用于发表评论; 产品需求是答题时不能粘贴(专治懒癌学生), 其二对输入不做限制;百度搜索,发现问题的关键在于textView的- (BOOL)canPerformAction:(SEL)action withSender:(id)sender方法,下面容我慢慢道来

脑子简单,没多想的后果

1、自定义了一个ForbidPasteTextView,添加是否禁止粘贴属性@property(nontamic,assign)BOOL forbidPaste,重写- (BOOL)canPerformAction:(SEL)action withSender:(id)sender

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if (self.forbidPaste && action==@selector(paste:)) {
        return NO;
    }
    return YES;
}

结果 :
长按输入框,粘贴的确没有出现,可是我看到了剪切、拷贝、全选、删除。。。。。。
更严重的是,我点击删除,程序崩溃了。。。


屏幕快照 2017-05-19 下午4.50.20.png

-[ForbidPasteTextView delete:]: unrecognized selector sent to instance 0x7ff2a1001200 , 这样一看我就明白了,真没我想的那么简单,既然重写- (BOOL)canPerformAction:(SEL)action withSender:(id)sender,那就是要付出代价的,写就要写完整咯,既然重写了菜单响应的方法,那菜单的点击方法也要写

修正,既然要重写菜单的方法,那么多,够用就行了,所以,除了粘贴,就留了剪切和拷贝
@implementation ForbidPoateTextView

//只禁止粘贴
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (self.forbidPaste && (action ==  @selector(paste:))) {
        return NO;
    }
    if (action == @selector(copy:) || action == @selector(paste:) || action == @selector(cut:)) {
        return YES;
    }else{
        return NO;
    }
    return YES;
}
- (void)copy:(UIMenuController *)menu
{
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    board.string = self.text;
    
}
- (void)paste:(UIMenuController *)menu
{
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    self.text = board.string;
}
- (void)cut:(UIMenuController *)menu
{
    [self copy:menu];
    self.text = nil;
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
屏幕快照 2017-05-19 下午5.05.29.png
放大招, 完全自定义自己的MenuController
//返回YES,会调起菜单  内部可以自定义菜单UIMenuItem
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    UIMenuController *menuControl = [UIMenuController sharedMenuController];
    UIMenuItem *item = [[UIMenuItem alloc]initWithTitle:@"插入表情" action:@selector(insertFace:)];
    menuControl.menuItems = @[item];
   //保留系统的拷贝和粘贴菜单
    if (action==@selector(insertFace:) || action == @selector(copy:) || action == @selector(paste:)) {
        return YES;
    }
    return NO;
}
- (void)insertFace:(UIMenuController *)menu
{
    NSLog(@"插入表情");
}
- (void)copy:(UIMenuController *)menu
{
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    board.string = self.text;
    
}

- (void)paste:(UIMenuController *)menu
{
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    self.text = board.string;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

@end
屏幕快照 2017-05-19 下午5.15.31.png

谢谢!

推荐阅读更多精彩内容