【发布时间】:2014-02-10 06:39:28
【问题描述】:
我创建了一个UITextField,并且我想对 textfield(userName) 进行验证,以便只允许使用字符。如果用户输入了数字或特殊字符等字母以外的任何其他内容,则不应出现,并且应该有显示相同内容的通知。
【问题讨论】:
标签: ios iphone objective-c uitextfield
我创建了一个UITextField,并且我想对 textfield(userName) 进行验证,以便只允许使用字符。如果用户输入了数字或特殊字符等字母以外的任何其他内容,则不应出现,并且应该有显示相同内容的通知。
【问题讨论】:
标签: ios iphone objective-c uitextfield
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *blockedCharacters = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
if (!([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound)) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Only allow alphabet." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[alert show];
}
return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
【讨论】:
你可以试试这个:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==YOUR_TEXTFIELD_NAME)
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Numbers not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
}
return YES;
}
确保为文本字段设置委托。
【讨论】:
try this
NSCharacterSet *blockedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
【讨论】:
#define ACCEPTABLE_NUMBER @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *acceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_NUMBER]invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:acceptedInput] componentsJoinedByString:@""];
if ((![filtered isEqualToString:string]))
return NO;
}
}
【讨论】: