项目上有个输入税号的需求,要求只能输入字母和数字,并且字母只能是大写字母
一、只能输入字母和数字
1.首先设置键盘样式
self.textField.keyboardType = UIKeyboardTypeASCIICapable;
2.设置宏
#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
3.textFieldDelegate方法
// 只能输入字母和数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
// 小写字母转大写字母
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.text = [textField.text uppercaseString];
}
二、字数限制
TextField字数限制,比如只能输入25个字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.titleTextField) {
// 这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
} else if (self.titleTextField.text.length >= 25) {
self.titleTextField.text = [textField.text substringToIndex:25];
return NO;
}
}
return YES;
}