項(xiàng)目上有個(gè)輸入稅號(hào)的需求精盅,要求只能輸入字母和數(shù)字朽色,并且字母只能是大寫(xiě)字母
一、只能輸入字母和數(shù)字
1.首先設(shè)置鍵盤(pán)樣式
self.textField.keyboardType = UIKeyboardTypeASCIICapable;
2.設(shè)置宏
#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
3.textFieldDelegate方法
// 只能輸入字母和數(shù)字
- (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];
}
// 小寫(xiě)字母轉(zhuǎn)大寫(xiě)字母
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.text = [textField.text uppercaseString];
}
二、字?jǐn)?shù)限制
TextField字?jǐn)?shù)限制愕掏,比如只能輸入25個(gè)字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.titleTextField) {
// 這里的if時(shí)候?yàn)榱双@取刪除操作,如果沒(méi)有次if會(huì)造成當(dāng)達(dá)到字?jǐn)?shù)限制后刪除鍵也不能使用的后果.
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;
}