通过UITabBarController让目标VC知道当前VC是委托的

我正在尝试将 destinationVC currentVC 设置为 delegate ,该导航将通过 UITabBarController ,并嵌入到 UINavigationController 中。

我不能将当前的VC设置为委托,因为 prepareForSegue 永远不会触发,并且提供的其他解决方案也不起作用(底部代码)。

所有这些都通过 Interface-builder

设置为 Storyboards

这是架构:

  

-> UITabBarController

     
    

-> UINavigationController

         
      

-> currentVC(将其设置为委托)

    
         

-> UINavigationController

         
      

-> destinationVC

    
  

这什么都不做:

override func prepare(for segue: uistoryboardSegue,sender: Any?) {

   print ("The Segue was triggered")
   let destinationVC = segue.destination as! MyViewController
   destinationVC.delegate = self

}

我也无法使它正常工作(它永远不会通过IF语句):

override func viewDidLoad() {
        super.viewDidLoad()

        if let myDestinationVC = (self.tabBarController?.viewControllers![0] as? UINavigationController)?.viewControllers[0] as? destinationVC {
            print ("The IF statement was triggered")
            myDestinationVC.delegate = self
        }
}

我有一个用于TabBarController的自定义类,该类现在实际上并没有执行任何操作-我不确定是否需要在上面的代码中引用它?

asdqq 回答:通过UITabBarController让目标VC知道当前VC是委托的

这是一个可行且经过测试的实现。并非实现此目的的最佳方法,但可以满足您的描述。

class MyTabBarViewController: UITabBarController,UITabBarControllerDelegate {

    // Replace with your sending view controller class's type
    var sendingViewController: SendingViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self

        // Iterate all view controllers to make sure they are instantiated and
        // get reference to the sendingViewController
        viewControllers?.forEach {
            if let navigationController = $0 as? UINavigationController {
                // Replace with the type of your sending view controller
                if let sendingViewController = navigationController.topViewController as? SendingViewController {
                    self.sendingViewController = sendingViewController
                }
            }

        }
    }

    func tabBarController(_ tabBarController: UITabBarController,didSelect viewController: UIViewController) {

        if let navigationController = viewController as? UINavigationController {
            // Replace with the type of your receiving view controller
            if let receivingViewController = navigationController.topViewController as? ReceivingViewController,let sendingViewController = sendingViewController {
                // Perform actions here
                receivingViewController.view.backgroundColor = sendingViewController.view.backgroundColor
            }
        }
    }
}
本文链接:https://www.f2er.com/2898413.html

大家都在问