迅速-从UIAlertController操作中取消视图控制器可防止视图控制器取消初始化

时间:2018-07-18 05:20:53

标签: swift

按下关闭按钮,我正在运行这段代码

        let alert = UIAlertController(title: "Hey!", message: "What to do?", preferredStyle: UIAlertControllerStyle.actionSheet)

        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { [weak self]_ in

            self?.alert.dismiss(animated: true)

        })

        let closeAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: {[weak self] _ in

             self?.dismiss(animated: true, completion: nil)

        })

        alert.addAction(cancelAction)
        alert.addAction(closeAction)

        self.present(alert, animated: true)

如果用户按下关闭动作,则视图控制器(自身)将不会取消初始化。

1 个答案:

答案 0 :(得分:0)

解决方案是在关闭视图控制器之前,在视图控制器上保留UIAlertContorller的引用并使其无效。

self.alert = UIAlertController(title: "Hey!", message: "What to do?", preferredStyle: UIAlertControllerStyle.actionSheet)

let closeAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: {[weak self] _ in

    self?.alert = nil
    self?.dismiss(animated: true, completion: nil)

})