从弹出视图 swift 移至根目录 ViewController

Move to root ViewController from popup view swift

我看过类似的问题,但找不到合适的答案。我现在发送一个视图我想在单击按钮时从该视图移动到根视图控制器。 self.navigationController?.popToRootViewController(animated: true) 不工作。

也试过下面的代码,但它对我不起作用。

UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
(appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
}

好的,这里是创建一个协议的解决方案,它向符合它的任何人抛出一个委托,这样控制器就可以知道按钮被单击了,所以你的父控制器有导航控制器,它将把你弹出到根视图控制器

在你的 popvc.swift

    protocol PopupDelegate : AnyObject{
        func buttonTapped(_ status : Bool)
    }
    
    class popUpVc: UIViewController {
    
        weak var delegate : PopupDelegate?
    
     @IBAction func btnLoginAction(_ sender: Any) {
    
      self.delegate?.buttonTapped(true)
      self.dismiss(animated: true, completion: nil)
    
     }
    
    }

现在在显示弹出窗口的父视图控制器中

        let vc = self.storyBoard.instantiateViewController(withIdentifier: "WaitingVc") as! WaitingVc
        vc.delegate = self
        self.present(vc, animated: true, completion: nil)

像这样遵守协议

extension yourParentVC : PopupDelegate{

func PopupDelegate(_ status: Bool) {
if status{
  self.navigationController?.popToRootViewController(animated: true)
   }

}

记得每次使用

self.delegate?.buttonTapped(true)

parentVc 会把你弹出来,这样你就可以使用延迟或其他东西,或者可以在完成关闭时调用该行,以免错过动画。