Swift 通过 UITabBarController 访问 viewController 的函数

Swift accessing a function of a viewController through a UITabBarController

我有一个 tableView 需要更新。如此处另一个问题所述:

总之。正确答案最终与我原来的问题完全无关,有人建议我提出另一个问题,关于如何为我需要调用的特定 viewController 调用函数。

这是我的控制器设置。

NavigationController
   ContainerViewController. (2 childViewControllers)
      menuTabBarController (this is a UITabBarController)
         SuggestionsViewController (This is the viewController I need to run a function from)
         ...
      SideBarViewController

UITableView 的 viewController 是 suggestionsViewController

我需要运行的viewController函数是SideBarViewController

我要调用的函数叫做 loadSuggestions()

我的第一次尝试当然只是 运行ning:

SuggestionsViewController().loadSuggestions()

但是正如我在其他问题中所解释的那样。这将创建它的一个新实例,而不是 运行ning loadSuggestions() 在 viewController 上我想更新我的 UITableView

帮助推断出为什么 UITableView 没有更新的问题的用户 (rdelmar) 向我指出了 /right/ 方向,我得到了以下代码:

(menuTabBarController.viewControllers as! [UIViewController])[0]

不过。我目前的问题是,我无法从

访问 loadSuggestions()

所以。简而言之。当我点击滑出式菜单上的按钮时,我需要使用函数 loadSuggestions() 更新我的 UITableView

如何做到这一点?

如果 (menuTabBarController.viewControllers as! [UIViewController])[0] 是正确的视图控制器,您可以转换它 as SuggestionsViewController,只要它不是私有方法,您就可以调用该方法。

您无法使用已有的方法调用该方法,因为您得到的是 UIViewController 的数组,并且 UIViewController 没有 loadSuggestions 方法。