James
James

Reputation: 333

In iOS, how can I disable pasting into a UITextfield or other input field?

I am aware of the solutions listed here:

How to disable copy paste option from UITextField programmatically

and here:

UITextField how to disable the paste?

but that isn't exactly what I want to do. I feel it is a little messy because the user can still tap and hold the text field and see the paste option is available. If the user taps it, the textfield just won't resound to that action.

I want to actually remove the "Paste" option from the list of options that comes up. Is that possible? Any direction would be greatly appreciated. Thanks in advance.

Upvotes: 2

Views: 4238

Answers (3)

Hardik Mamtora
Hardik Mamtora

Reputation: 1652

Use below Method

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
     //Do your stuff
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{
     [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
     }];
     return [super canPerformAction:action withSender:sender];
}

Upvotes: 0

Serhiy
Serhiy

Reputation: 331

Another way is subclassing UITextField and overriding canPerformAction:withSender: method like described in Adding a dynamic custom UIMenuItem to Copy & Paste Menu before it shows

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

Upvotes: 1

hiwordls
hiwordls

Reputation: 781

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if(textField == txtCardNumber)
    {
        if([string length]>1){
            //Disable to paste action
            return NO;

        }
     }
}

Upvotes: 2

Related Questions