PresentViewController 不起作用:视图不在 TabBarController 的 window 层次结构中

PresentViewController does not work: view is not in the window hierarchy in TabBarController

我创建了一个 CustomAlertView。

protocol CustomAlertViewControllerDelegate{
    func retryToFetchData()
}

class CustomAlertViewController: UIViewController {

    @IBOutlet weak var alertView: UIView!
    var delegate: CustomAlertViewControllerDelegate!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.alertView.alpha = 0
        self.alertView.frame.origin.y = self.alertView.frame.origin.y + 50

        UIView.animate(withDuration: 0.4) {
            self.alertView.alpha = 1.0
            self.alertView.frame.origin.y = self.alertView.frame.origin.y - 50
        }
    }


    @IBAction func retryButton(_ sender: UIButton) {
        delegate?.retryToFetchData()
        self.dismiss(animated: true, completion: nil)
    }

}

我创建了一个静态函数来显示该视图。该视图只是一个 UIViewController,它将有一个子视图,该子视图将充当弹出窗口,具有透明背景。

func showErrorBox(view: UIViewController, message: String, delegate: CustomAlertViewControllerDelegate){ 

    let customAlert = view.storyboard?.instantiateViewController(withIdentifier: "customAlertViewController") as! CustomAlertViewController
    customAlert.providesPresentationContextTransitionStyle = true
    customAlert.definesPresentationContext = true
    customAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    customAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    customAlert.delegate = delegate
    view.present(customAlert, animated: true, completion: nil)
}

现在,我在需要使用 showErrorBox(view: self, message: message, delegate: self) 显示弹出窗口的任何地方调用此 VC 现在我的问题是我需要在 ViewController 中显示此弹出窗口一个 TabBarController,当我在 UITabBar 之间更改视图并尝试按下重新加载按钮时,应用程序抛出错误,

presentViewController does not work: view is not in the window hierarchy

编辑: ErrorBox(popUp) 上有一个 Retry 按钮。只有在加载错误框并且我将视图更改为不同的选项卡然后点击重新加载按钮时才会发生错误。在正常情况下,当我在同一页面时点击重新加载按钮工作正常。

我不确定是不是问题,但这与我在出现错误框时更改选项卡之间的视图有关。

尝试获取 TopMost ViewController 并从中显示 CustomAlertViewController 而不是 "self"。

将此 link 参考给: GetTopMostViewController

尝试 self.present(customAlert, animated: true, completion: nil) 而不是 view.present(customAlert, animated: true, completion: nil)。如果我理解你的问题,应该可以

解决方案,

问题是,当我更改 TabController 中的视图时,对 customAlertView 的引用已从 window 层次结构中删除。因此,一旦我离开正在加载的 TabView,就需要删除 CustomAlertView。

为了解决这个问题,我在CustomAlertViewController

中添加了以下代码
override func viewWillDisappear(_ animated: Bool) {
    super. viewWillDisappear(animated)
    self.dismiss(animated: true, completion: nil)
}