关闭视图控制器,然后显示警报控制器

问题描述 投票:0回答:4

在我的项目中,我使用rootViewController?.dismiss将一些视图控制器关闭回主VC。

在完成处理程序中,我想在主视图控制器再次可见时呈现UIAlertController。

我的问题是UIAlertController永远不会出现。我的预感是因为我在launchFrom参数中使用self。我是否需要获得对主VC的引用,并将其呈现在那里?

解散VC并尝试提示警报:

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
    Constants.presentThankYou(launchFrom: self)
})

presentThankYou方法

static func presentThankYou(launchFrom: UIViewController) {
    let alertController = UIAlertController(title: "Thank You!", message: "You did it!", preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
        print("Done")
    }
    alertController.addAction(okAction)
    launchFrom.present(alertController, animated: true, completion: nil)
}

在我的所有VC被解雇后,如何呈现警报控制器?

ios swift uialertcontroller rootviewcontroller
4个回答
2
投票

在我的脑海中,尝试在viewDidAppear做。要防止警报一直显示,请使用bool shouldShowThankYouAlert并在dismiss completion处理程序中将此值设置为true


1
投票

如果需要,你也可以参考这个,只需调用警报显示在被解雇的Controller的viewWillDisappear中

override func viewWillDisappear(_ animated: Bool) {
        if self.isMovingFromParentViewController {
            DispatchQueue.main.async {
                wrapperClass.BasicAlert("View is Dismissed", message: "", view: self)
            }
        }
    }

当视图被完全关闭时,这将显示警报


0
投票

我没有检查,但如何使用窗口而不是UIViewController。

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
   Constants.presentThankYou()
})

static func presentThankYou() {
   let alertController = UIAlertController(title: "Thank You!", message: "You did it!", preferredStyle: UIAlertControllerStyle.alert)
   let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
       print("Done")
    }
   alertController.addAction(okAction)
   appDelegate.window.present(alertController, animated: true, completion: nil)
}

-1
投票

所以一个问题是,完成块不需要主线程。我建议强制完成执行一些代码。

var topController: UIViewController? {
  if var temp = UIApplication.shared.keyWindow?.rootViewController {
    while let presentedViewController = temp.presentedViewController {
      temp = presentedViewController
    }
    return temp
  }
  return nil
}

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
  DispatchQueue.main.async {
    guard let top = topController else { return }
    Constants.presentThankYou(launchFrom: top)
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.