由于 presentViewController,警报不工作

Alert not working due to presentViewController

似乎在我的 UIViewController 中调用 Alert 会导致 presentViewController 出现问题(...由于可能无意中尝试快速连续两次呈现相同的视图控制器...)。

我该怎么做才能解决这个问题(...请参阅下面的代码)???

错误信息:

<MyApp.MyViewController: 0x67544325620> which is already presenting (null)

代码:

func textFieldShouldEndEditing(textField: UITextField) -> Bool {

    if (textField.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 5) {

        var alert = UIAlertController(title: "Warning", message: "Only Initials with maximal 5 letters allowed!", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

        // that is where the problem seems to occur.... !!! Why ????
        self.presentViewController(alert, animated: true, completion: nil)

        return false
    }
    return true
}

不要完全使用此代码,请修改以适合您的情况。这是一个可以帮助您了解并预防问题的示例:

    var alert = UIAlertController(title: "Warning", message: "Only Initials with maximal 5 letters allowed!", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

    // assuming that this is the first time your controller is presented

    println("is presenting \(presentedViewController)") //is nil

    presentViewController(alert, animated: true, completion: nil)

    //is now not nil
    println("is presenting \(presentedViewController)")        

    //something bad happened and your application is trying to present the alert again, safe guard against presenting it twice by checking if presentedViewController is nil or not
    if presentedViewController == nil {
        presentViewController(alert, animated: true, completion: nil)
    }

您只需要在顶视图控制器 (presentedViewController) 上呈现警报。

尝试使用以下代码显示 UIAlertViewController

呼叫以下线路:

 [self showMessage:@"Message" withTitle:@"Title"];

方法:

  -(void)showMessage:(NSString*)message withTitle:(NSString *)title
    {
        UIAlertController * alert=   [UIAlertController
                                      alertControllerWithTitle:title
                                      message:message
                                      preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

            //do something when click button
        }];
        [alert addAction:okAction];
        [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alert animated:YES completion:nil];
    }