开发者

Restricting copy,paste option for a particular UITextfield

开发者 https://www.devze.com 2023-01-27 03:55 出处:网络
My UIView contains Two UITextField.I need to restrict copy,paste option for one textfield.I don\'t want to restrict that for another.

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)canPerformA开发者_JAVA百科ction:(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.


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.


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


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消