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 options for copying / pasting a text field, how to disable menu options for a specific text field.

+8
ios objective-c uitextfield
source share
4 answers

I think this method is fine, since there is no category creation, etc. It works great for me.

  [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO]; }]; return [super canPerformAction:action withSender:sender]; 
+13
source share

You must subclass UITextView and override canPerformAction:withSender . Text fields that should not 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 Quick 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) } } 
+8
source share

Subclass 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 
+2
source share

In your implementation, you should check if the sender is your exact text field, which should be disabled:

 @implementation UITextField (DisableCopyPaste) - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if ((UITextField *)sender == yourTextField) return NO; return [super canPerformAction:action withSender:self]; } @end 

But it’s not good to make a category that redefines a method. It is better if you create a new class, for example SpecialTextField , which inherits UITextField , which will always have a return NO method for canPerformAction: withSender: and set this class only to text fields that should be disabled for copy / paste.

0
source share

All Articles