1.只让输入的字母变大写
- 方法一
- (void)viewDidLoad {
[super viewDidLoad];
_plateTextField = [[UITextField alloc] init];
_plateTextField.delegate = self;
[_plateTextField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldChanged:(UITextField *)textField{
textField.text = [textField.text uppercaseString];
}
- 方法二
- (void)viewDidLoad {
[super viewDidLoad];
_plateTextField = [[UITextField alloc] init];
_plateTextField.delegate = self;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([self isBlankString:string]) {
return YES;
}
char commitChar = [string characterAtIndex:0];
if (commitChar > 96 && commitChar < 123) {
//小写变成大写
NSString * uppercaseString = string.uppercaseString;
NSString * str1 = [textField.text substringToIndex:range.location];
NSString * str2 = [textField.text substringFromIndex:range.location];
textField.text = [NSString stringWithFormat:@"%@%@%@",str1,uppercaseString,str2];
return NO;
}
}
// 判断字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
if (string == nil || string == NULL) {
return YES;
}
if ([string isKindOfClass:[NSNull class]]) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
return YES;
}
return NO;
}
2.限制只能输入字母 + 输入后自动变大写 + 限制输入字母个数
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (void)viewDidLoad {
[super viewDidLoad];
_plateTextField = [[UITextField alloc] init];
_plateTextField.delegate = self;
[_plateTextField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldChanged:(UITextField *)textField{
textField.text = [textField.text uppercaseString];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
/* 你想限制输入的字母个数 */
NSInteger textLength = 5;
if ([textField isEqual:self.plateTextField]) {
NSCharacterSet *cs;
cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL canChange = [string isEqualToString:filtered];
return proposedNewLength>textLength ? NO: canChange;
}
return YES;
}
网友评论