使用 UIAlertAction 关闭视图控制器

Dismiss a View Controller with a UIAlertAction

我正在尝试显示注销警报。当用户点击 Yes 时,我希望我的视图控制器使用可以为我提供完成处理程序的方法关闭。

视图控制器位于导航控制器内,是堆栈中的第二个。

我想出了以下代码:

@IBAction func logOut() {
        let logOutAlert = UIAlertController.init(title: "Log out", message: "Are you sure ?", preferredStyle:.Alert)

        logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
            //Present entry view ==> NOT EXECUTED
            self.dismissViewControllerAnimated(true, completion:nil)
        })

        logOutAlert.addAction(UIAlertAction.init(title: "Cancel", style: .Cancel, handler: nil))

        self.presentViewController(logOutAlert, animated: true, completion: nil)
}

已读取第 self.dismissViewControllerAnimated(true, completion:nil) 行,但未执行任何操作。

我怀疑 dismissViewControllerAnimated 不会为您做任何事情,因为视图控制器不是模态显示的,而是通过导航控制器显示的。要关闭 is,您可以告诉导航控制器将其从堆栈中弹出,如下所示:

    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        self.navigationController?.popViewControllerAnimated(true)
        })

不幸的是,popViewControllerAnimated 似乎没有提供一种开箱即用的方法来附加您自己的完成处理程序。如果您需要一个,您仍然可以使用关联的 CATransaction 添加一个,它看起来像这样:

    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        CATransaction.begin()
        CATransaction.setCompletionBlock(/* YOUR BLOCK GOES HERE */)
        self.navigationController?.popViewControllerAnimated(true)
        CATransaction.commit()
        })