首页 > 代码库 > IOS-如何干掉UITextField的长按手势菜单与输入内容限制
IOS-如何干掉UITextField的长按手势菜单与输入内容限制
今天项目用到了这个就写一下,方便以后同学不会的时候可以直接使用
首先要重写UITextFiled子类 在初始化方法下面 copy 下面方法 就禁止了长按出现的菜单
//干掉textField 的长按菜单 禁止copy paste
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if ([UIMenuControllersharedMenuController]) {
[UIMenuControllersharedMenuController].menuVisible =NO;
}
return NO;
}
在开发中我们有时候会对UITextFiled 进行一些操作,说一下如何只输入中文,或者 只输入 数字 和英文 2中方法
我直接用宏定义定义:
#define kAlphaNum @"abcdefghijklmnopqrstuvwxyz" //这种是对应只输入中文 不允许其他数字或者符号的
#define kEnglishNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" //这种是对应只能输入数字和英文的方法
执行UITextField 的delegate 方法 切记 textFiled.delegate = self;
下面直接上代码:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{UITextField *nameField = (UITextField *)[selfviewWithTag:200];
UITextField *cardField = (UITextField *)[selfviewWithTag:201];
if (textField == nameField) {
//只允许输入中文
NSCharacterSet *cs;
cs = [[NSCharacterSetcharacterSetWithCharactersInString:kAlphaNum]invertedSet];
NSString *filtered = [[stringcomponentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basic = [string isEqualToString:filtered];
NSString *text = [textField.textstringByReplacingCharactersInRange:range withString:string];
if (_delegate && [_delegaterespondsToSelector:@selector(passName:)]) {
[_delegatepassName:text];
}
return basic;
}
if (textField == cardField) {
//只允许输入英文和数字
NSCharacterSet *cs;
cs = [[NSCharacterSetcharacterSetWithCharactersInString:kEnglishNum]invertedSet];
NSString *filtered = [[stringcomponentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basic = [string isEqualToString:filtered];
NSString *text = [textField.textstringByReplacingCharactersInRange:range withString:string];
if (_delegate && [_delegaterespondsToSelector:@selector(passCard:)]) {
[_delegatepassCard:text];
}
return basic;
}
return YES;
}
IOS-如何干掉UITextField的长按手势菜单与输入内容限制