在我的iOS应用程序中,我有一个UITextField,它目前将其字符输入限制为50个字符,当它收到一个字符时,它启用一个UIButton。我现在要做的是确保用户也只能输入字母数字字符,但这是我遇到麻烦的地方。这是我到目前为止的代码:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet];
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if (newLength > 0) {
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
canEdit=NO;
self.myButton.enabled = NO;
}
else
{
canEdit=YES;
self.myButton.enabled = YES;
}
}
} else self.myButton.enabled = NO;
return (newLength > 50 && canEdit) ? NO : YES;
}
最初,我的代码只是将字符输入限制为只有50个字符,启用我的按钮如下所示:
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if (newLength > 0) self.doneButton.enabled = YES;
else self.doneButton.enabled = NO;
return (newLength > 45) ? NO : YES;
我想说的是,我想在现有代码中加入字母数字字符的限制,而不是替换它。这对我来说是一个具有挑战性的部分。
答案 0 :(得分:1)
当字符是非字母数字字符时,您将需要循环并向该方法返回NO。所以,你拥有的代码应该是:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
BOOL canEdit=NO;
NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if (newLength > 0) {
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
canEdit=NO;
self.myButton.enabled = NO;
}
else
{
canEdit=YES;
self.myButton.enabled = YES;
}
}
} else self.myButton.enabled = NO;
return (newLength > 50 && canEdit) ? NO : YES;
}