程序员人生 网站导航

要求UItextField指数如中文、数字、英文

栏目:综合技术时间:2015-05-14 09:30:37

在开发中我们有时候会对UITextFiled 进行1些操作,说1下如何只输入中文,或 只输入 数字 和英文 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 *)[self viewWithTag:200];

UITextField *cardField = (UITextField *)[self viewWithTag:201];


if (textField == nameField) {

//只允许输入中文

NSCharacterSet *cs;

cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];

NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

BOOL basic = [string isEqualToString:filtered];

NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

if (_delegate && [_delegate respondsToSelector:@selector(passName:)]) {

[_delegate passName:text];

}

return basic;

}


if (textField == cardField) {


//只允许输入英文和数字

NSCharacterSet *cs;

cs = [[NSCharacterSet characterSetWithCharactersInString:kEnglishNum] invertedSet];

NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

BOOL basic = [string isEqualToString:filtered];

NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

if (_delegate && [_delegate respondsToSelector:@selector(passCard:)]) {

[_delegate passCard:text];

}

return basic;

}

return YES;


}


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐