Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable copy/paste option in UITextfield in ios7

I tried

@implementation UITextField (DisableCopyPaste)

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

return NO;
return [super canPerformAction:action withSender:sender];
 }

@end

But it disables all textfield's copy/paste option,how to disable the menu options for specific textfield.

like image 515
SMS Avatar asked Jun 09 '14 07:06

SMS


3 Answers

I think this method is ok,since no making of category etc.It works fine for me.

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
    }];
    return [super canPerformAction:action withSender:sender];
like image 179
SMS Avatar answered Nov 12 '22 01:11

SMS


You should subclass UITextView and override canPerformAction:withSender. Text fields that shouldn't provide copy/paste should be defined with your subclass.

NonCopyPasteField.h:

@interface NonCopyPasteField : UITextField
@end

NonCopyPasteField.m:

@implemetation
  (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copy:) || action == @selector(paste:)) {
      return NO;
    }
    [super canPerformAction:action withSender:sender];
  }
@end

Update. Swift version:

class NonCopyPasteField: UITextField {
  override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if (action == #selector(copy(_:)) || action == #selector(paste(_:))) {
      return false
    }
    return super.canPerformAction(action, withSender: sender)
  }
}
like image 26
Ilia Avatar answered Nov 12 '22 00:11

Ilia


Create a sub class for UITextField and overwrite the method and use it wherever you want.

@interface CustomTextField: UITextField
@end

@implemetation CustomTextField
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    //Do your stuff
}
@end
like image 42
jailani Avatar answered Nov 12 '22 00:11

jailani