swift 如何检查弹出ViewController后,堆栈顶部的ViewController,是一个特定的?

1yjd4xko  于 2023-08-02  发布在  Swift
关注(0)|答案(3)|浏览(131)

假设我现在在BaseViewController上。我可以从另外两个视图控制器,比如A和B,接近这个视图控制器类。那么,当我弹出BaseViewController时,如何检查堆栈顶部是否存在A或B?下面是我的代码(在BaseViewController中):

func goToAOrBViewController {
   // If after popping viewController is A do this
   navigationController.popViewController(animated: true)
   // If after popping viewController is B do this
   // Instantiate B and push it
}

字符串

bhmjp9jg

bhmjp9jg1#

有很多方法可以做到这一点
最简单的方法

func visibleViewController() -> UIViewController? {
        let appDelegate = UIApplication.shared.delegate
        if let window = appDelegate!.window {
            return window?.visibleViewController
        }
        return nil
    }

    func goToAOrBViewController {
       // If after popping viewController is A do this
       navigationController.popViewController(animated: true)
       if visibleViewController() == viewControllerA{
           //Do stuff for A
       }else{
           //Do stuff for B
       }
    }

字符串
第二种显而易见的方法

let topController = UIApplication.sharedApplication().keyWindow?.rootViewController
    if topController == viewControllerA {
        //Do stuff for A
    }else{
        //Do stuff for B
    }

fcwjkofz

fcwjkofz2#

可以同时弹出和推送视图控制器。
未检测:

navigationController?.viewControllers.removeLast()
let topVC = navigationController?.viewControllers.last

if topVC == A {
  navigationController?.viewControllers.append(A)
  navigationController?.setViewControllers(A, animated: false)
} else {
  navigationController?.viewControllers.append(B)
  navigationController?.setViewControllers(B, animated: false)
}

字符串

new9mtju

new9mtju3#

BaseViewController类内部:

func goToAOrBViewController() {
   guard let navigationController = self.navigationController else { return }
   navigationController.popViewController(animated: false)
   guard let viewController = navigationController.topViewController else { return }
   if viewController is ViewControllerA {
      // Do something for A
   } else if viewController is ViewControllerB {
      // Do Something for B
   }
   // You need not put else-if case if you are sure BaseVC is reachable from A and B only (just use else)
}

字符串

相关问题