由于presentViewController,警报无法正常工作

时间:2015-05-17 19:14:30

标签: ios uiviewcontroller uialertcontroller

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

我该怎么办?(见下面的代码)???

错误讯息:

<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
}

3 个答案:

答案 0 :(得分:0)

请勿完全使用此代码,请根据您的具体情况进行修改。这是一个可以帮助您理解并防止出现问题的示例:

    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)
    }

答案 1 :(得分:0)

您只需要在顶视图控制器(presentsViewController)上显示警报。

答案 2 :(得分:0)

尝试使用以下代码来显示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];
    }