我正在执行一个条件语句,该语句检查文本字段是否包含某些字符,如果包含这些字符,则会显示UIAlertView。目前,如果文本字段包含字母,则会显示警报,我将如何扩展下面的方法以包括字符,如?!,$等
if ([self.withdrawTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
试试这个:
NSMutableCharacterSet *mcs1 = [[NSCharacterSet letterCharacterSet] mutableCopy];
[mcs1 addCharactersInString:@"?!.$"];
if ([self.withdrawTextField.text rangeOfCharacterFromSet:mcs1].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
由于您只想在字符串中使用数字和句点,因此可以尝试下面的代码。它可能会对你有所帮助。
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
for (int i = 0; i < [[self.withdrawTextField.text length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Ooops" message:@"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}