如何在此代码中限制UIalertview?

时间:2015-03-18 14:27:39

标签: ios uialertview

我创建了一个美国格式的手机号码。此代码不显示字母和特殊字符。它已成功显示但显示UIAlertviews,当用户在UITextfield中输入字母和特殊字符时,会显示一些UIAlertview。如何控制UIAlertviews?我只想显示一个Alertview

这是我已有的代码:

if(textField==mobileNo)
    {
        NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

        for (int i = 0; i < [string length]; i--) {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                return NO;
            }                
        }       
    }

3 个答案:

答案 0 :(得分:2)

你可以试试以下......但它不是一个很好的解决方案......

在标题中声明一个BOOL来检查警报视图是否已经显示,如下所示:

BOOL alertCheck;

在viewDidLoad中将其设置为NO:

alertCheck = NO;

然后在您的代码中,在决定显示您的警报视图之前检查它。

if(textField==mobileNo) { 

    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

    for (int i = 0; i < [string length]; i--) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            if (alertCheck == NO) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];

                alertCheck = YES;
            }
            return NO;
        }

    }

}

答案 1 :(得分:0)

您可以尝试以下操作:

if (![myCharSet characterIsMember:c]) {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //show the UIAlertView
    });
}

答案 2 :(得分:0)

那段代码并不是那么好。您只是检查字符串值是否为数字。为此,您可以这样使用[NSScanner scannerWithString:]

 bool isNumber = [[NSScanner scannerWithString: string] scanInt:nil]
 if (!isNumber) {
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
     [alert show];
  }

代码似乎更清晰,更简单。

希望它有所帮助!