我想限制輸入爲用戶名字段的英文字母(a-z)。有人可以幫助我添加下面的代碼,不允許輸入任何數字,字符和任何其他語言,而不是英文字母嗎?UITextField只允許英文字母輸入
現在下面的代碼不允許使用空格,也不允許輸入超過10個字母。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
{
BOOL _isAllowed = YES;
NSString *nameRegex = @"[A-Za-z]+";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
NSString *tempString = [[textField.text stringByReplacingCharactersInRange:range withString:string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (textField == self.usernameField)
{
if ([self.usernameField.text isEqualToString:tempString])
{
self.title.text = @"No Spaces Allowed";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
else if (tempString.length > 10)
{
self.title.text = @"Username cannot be more than 10 letters.";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
修訂:
else if (![nameTest evaluateWithObject:self.usernameField.text])
{
self.title.text = @"Username can only contain english letters.";
self.title.textColor = [UIColor yellowColor];
_isAllowed = NO;
}
return _isAllowed;
}
return _isAllowed;
}
感謝。
它不允許使用退格鍵來刪除第一個字符。 – Shmidt 2014-07-27 09:00:48