Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

前端 未结 17 989
花落未央
花落未央 2020-11-30 22:03

I\'m trying to present a ViewController if there is any saved data in the data model. But I get the following error:

Warning: A

17条回答
  •  孤城傲影
    2020-11-30 22:12

    Swift 3.

    Call this function to get the topmost view controller, then have that view controller present.

    func topMostController() -> UIViewController {
        var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
            while (topController.presentedViewController != nil) {
                topController = topController.presentedViewController!
            }
            return topController
        }
    

    Usage:

    let topVC = topMostController()
    let vcToPresent = self.storyboard!.instantiateViewController(withIdentifier: "YourVCStoryboardID") as! YourViewController
    topVC.present(vcToPresent, animated: true, completion: nil)
    

提交回复
热议问题