How to disable copy/paste option in UITextfield in ios7

回眸只為那壹抹淺笑 提交于 2019-12-22 04:26:06

问题


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.


回答1:


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



回答2:


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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/24115269/how-to-disable-copy-paste-option-in-uitextfield-in-ios7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!