iOS中如何实现TextView仅可粘贴不可输入的功能

思路来源http://stackoverflow.com/questions/1920541/enable-copy-and-paste-on-uitextfield-without-making-it-editable

注意:此方法仅支持iOS6.0或者更新,5.0系统因粘贴触发机制不同,如果设置editable为NO,那么长按时并不会触发-- (BOOL)canPerformAction:(SEL)action withSender:(id)sender方法。如需支持6.0以下系统,请特别注意。

首先从UITextView继承一个子类并重写以下方法:

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:)) {
        return YES;
    }else{
        return [super canPerformAction:action withSender:sender];
    }
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    if ([super becomeFirstResponder]) {
        return YES;
    }
    return NO;
}

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


然后在实例化时将textView的eidable属性设为NO即可;

你可能感兴趣的:(粘贴,disable,UITextView,keyboard,only,paste,不能输入)