如何从UICollectionView单元引用选项卡栏控制器

我有一个标签栏控制器应用程序,并在其中一个选项卡UI集合视图控制器与操作分配给一个button。 这个button会发挥它的魔力,然后将标签栏视图更改为另一个。 但是,我无法正确引用选项卡控制器。

tabBarController是分配给控制器的类名。 所以,我试过了:

tabBarController.selectedIndex = 3 

并直接在tabBarController类中创build一个方法

 tabBarController.goToIndex(3) 

错误说:'goToIndex'的实例成员不能用在tabBarControllertypes上

任何意识?

谢谢,

我通过引用它理解你的意思有点麻烦,但希望这会有所帮助。 假设tabBarController是UITabBarController的一个子类:

 class MyTabBarController: UITabBarController { /// ... func goToIndex(index: Int) { } } 

在其中一个选项卡控制器(UIViewController)中,您可以使用self.tabBarController引用您的UITabBarController。 请注意,self.tabBarController是可选的。

  self.tabBarController?.selectedIndex = 3 

如果您的选项卡UIViewController是UINavigationController中的UIViewController,那么您将需要引用您的标签栏,如下所示:

 self.navigationController?.tabBarController 

要调用子类的函数,您需要将标签栏控制器转换为您的自定义子类。

  if let myTabBarController = self.tabBarController as? MyTabBarController { myTabBarController.goToIndex(3) } 

根据评论更新:

你是正确的,你不能访问单元格内的tabBarController,除非你把它作为单元本身(不推荐)或应用程序委托的属性。 或者,您可以使用UIViewController上的目标操作来每次在单元格内轻按button时调用视图控制器上的函数。

 class CustomCell: UITableViewCell { @IBOutlet weak var myButton: UIButton! } class MyTableViewController: UITableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReuseIdentifier", for: indexPath) as! CustomCell /// Add the indexpath or other data as a tag that we /// might need later on. cell.myButton.tag = indexPath.row /// Add A Target so that we can call `changeIndex(sender:)` every time a user tapps on the /// button inside a cell. cell.myButton.addTarget(self, action: #selector(MyTableViewController.changeIndex(sender:)), for: .touchUpInside) return cell } /// This will be called every time `myButton` is tapped on any tableViewCell. If you need /// to know which cell was tapped, it was passed in via the tag property. /// /// - Parameter sender: UIButton on a UITableViewCell subclass. func changeIndex(sender: UIButton) { /// now tag is the indexpath row if you need it. let tag = sender.tag self.tabBarController?.selectedIndex = 3 } }