繁体   English   中英

当ViewController不在Window层次结构中时,不显示Alert

[英]Don't show Alert when the ViewController is not in Window hierarchy

我有一个NavigationController ThirdViewController我正在执行一些任务,并且在失败时,我使用UIAlertController显示Alert消息。

有时,当我启动任务并返回到SecondViewController ,我会在SecondViewController上显示错误消息,然后单击OK,导航栏下方的所有内容都会变黑。 我只剩下导航栏,如果我再次回到FirstViewController ,它除了导航栏之外还有相同的黑色视图。

呈现不在窗口层次结构中的ViewController的警报会产生问题。 如果我不在屏幕上,我不希望显示警报。

如果我慢慢地滑动ViewController,它很容易重现。

处理它的最佳方法是什么?

分享我的代码,

ThirdViewController按钮操作

func buttonTapped() {
        APIManager.sharedManager.getDetails(completion: { (details ,error) -> Void in
            guard error == nil else {
                Alert.errorMsg(error!.localizedDescription, viewController: self, goBack: false)
                return
            }
            print(details)
        }
    }

class Alert: NSObject {

    /* Error message */
    class func errorMsg(message: String, viewController: UIViewController?, goBack: Bool = false) {
        let alertView = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (alert: UIAlertAction) -> Void in
            if goBack == true && viewController != nil {
                viewController!.navigationController?.popToRootViewControllerAnimated(true)
            }
        }
        alertView.addAction(action)
        let controller = viewController ?? UIApplication.sharedApplication().keyWindow?.rootViewController
        controller!.presentViewController(alertView, animated: true, completion: nil)
    }
}

我创建了一个CustomViewController并添加了一个属性' isUnloading '。 viewWillDisappear ,我设置了isUnloading = true 我在出示警报之前检查了房产。

由于您没有共享任何代码,我们不确切知道那里发生了什么。 但是,如果您不希望在视图控制器不在窗口层次结构中时显示警报,则可以在显示警报视图之前检查是否设置了viewController.view.window ,并仅在设置时显示它。

你可以做点什么,

class AlertHelper {
func showAlert(fromController controller: UIViewController) { 
    var alert = UIAlertController(title: "abc", message: "def", preferredStyle: .Alert)
    controller.presentViewController(alert, animated: true, completion: nil)
}
}

叫做警报,

var alert = AlertHelper()
alert.showAlert(fromController: self)

请参阅此链接以了解更多详情。

希望这会有所帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM