iOS development: disable UItextfield's select, select all, and paste functions

In the iOS development process, sometimes it is necessary to disable the select, select, and paste functions that come with UItextfield. For example, in the APP login interface, the account input box can be copied and pasted, but the password input box cannot be pasted.

The specific steps are very simple, but one thing that must be noted is that you must create a new UItextfield category or create a new subclass that inherits from UItextfield, so as to avoid conflicts with other UItextfields in the project, and then create a new category Or you can override the corresponding method in the subclass. There are two ways to disable the selection, selection, and paste functions of UItextfield. The first method is to disable some functions and customize the method to disable related functions; the second method is to disable all input box functions. The specific code As follows:





Finally, the detailed code is attached:

1.BasTextField.m file:

#import "BasTextField.h"
@implementation BasTextField
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
//Method 1:
// Disable the paste function
if (action == @selector(paste:))
return NO; //YES is to enable this function;
// disable selection function
if (action == @selector(select:))
return NO;
// disable select all function
if (action == @selector(selectAll:))
return NO ;
return [super canPerformAction:action withSender:sender];


//方法二:
// UIMenuController *menuController = [UIMenuController sharedMenuController];
// if(menuController) {
// [UIMenuController sharedMenuController].menuVisible=NO;
// }
// return NO;
}
@end


2. The .m file of the TestViewController class where it is used:

#import "TestViewController.h"
#import "BasTextField.h"
@interface TestViewController ()<UITextFieldDelegate>
@end
@implementation TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITextField * pswTF = [[BasTextField alloc] initWithFrame:CGRectMake(20,70,340,45)];
pswTF.placeholder = @"请输入密码";
[self.view addSubview:pswTF];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325197021&siteId=291194637