1

我正在做一个条件语句来检查文本字段是否包含某些字符,如果是,它们将显示 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];

}
4

2 回答 2

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];

}
于 2013-11-22T11:31:19.837 回答
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;
       }
}
于 2013-11-22T10:58:12.217 回答