SMS
SMS

Reputation: 558

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.

Upvotes: 10

Views: 9029

Answers (4)

Ilia
Ilia

Reputation: 1444

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)
  }
}

Upvotes: 9

SMS
SMS

Reputation: 558

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];

Upvotes: 13

o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

In your implementation you have to check if the sender is your exact textfield 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 is not good to make a category which overrides a method. It is better if you make a new class like SpecialTextField which inherits UITextField which will have the method always return NO for canPerformAction:withSender: and set this class to only the textfields which should have copy/paste disabled.

Upvotes: 0

jailani
jailani

Reputation: 2270

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

Upvotes: 3

Related Questions