EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 2707

Restricting copy,paste option for a particular UITextfield

My UIView contains Two UITextField.I need to restrict copy,paste option for one textfield.I don't want to restrict that for another.

When i am using the following code,Both the field gets restricted from copy,paste.

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender 
{
    if ( [UIMenuController sharedMenuController] )
    {
            [UIMenuController sharedMenuController].menuVisible = NO;
    }
     return NO;
}

Can any one provide me the solution to solve my problem.

Upvotes: 7

Views: 9713

Answers (4)

user2224531
user2224531

Reputation: 71

I had a random idea that worked perfectly on a text view. No reason why it wouldn't work on a text field.

I added the following to the text field I wanted to restrict.

  • Long Press Gesture Recognizer (1 touch)
  • Long Press Gesture Recognizer (2 touches)
  • Tap Gesture Recognizer (2 taps, 1 touch)
  • Tap Gesture Recognizer (3 taps, 1 touch)
  • Tap Gesture Recognizer (1 tap, 2 touches)

Then assigned the following code to it.

- (IBAction)cancelTouch:(id)sender {
    //do nothing
}

I can now still scroll through the textview but a long press or double tap now do absolutely nothing!

Upvotes: 1

bdhac
bdhac

Reputation: 359

The following prevents any string longer than 1 character to be pasted. String that is 1 character long will however get through (could be useful to some people - doesn't need subclassing).

First give your textField a delegate

myTextField.delegate = self; // OR [myTextField setDelegate:self];

Then add the following method to your ViewController

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

    if ( [string length] > 1) {
        return NO;
    }
    return YES;
}

Upvotes: 4

vodkhang
vodkhang

Reputation: 18741

Explanantion from Apple:

This default implementation of this method returns YES if the responder class implements the requested action and calls the next responder if it does not. Subclasses may override this method to enable menu commands based on the current state; for example, you would enable the Copy command if there is a selection or disable the Paste command if the pasteboard did not contain data with the correct pasteboard representation type.

So, the solution is to subclass the UITextView and return properly.

More information about the method here

Upvotes: 2

Lily Ballard
Lily Ballard

Reputation: 185663

Create a subclass of UITextField. In that subclass, implement

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (sel_isEqual(action, @selector(copy:))) {
        return NO;
    }
    return [super canPerformAction:action withSender:sender];
}

Then use this subclass for the field that you don't want to be able to copy in, and use a regular UITextField for the one that you can copy from.

Upvotes: 19

Related Questions