我正在做一个条件语句,检查文本字段是否包含某些字符,如果它是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];
}
答案 0 :(得分:2)
试试这个:
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];
}
答案 1 :(得分:0)
因为你只想在字符串中使用数字和点,而不是在代码下面尝试。它可能对你有帮助。
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;
}
}