如何从UICollectionView Cell中引用Tab Bar Controller

问题描述:

我有一个标签栏控制器应用程序,在其中一个选项卡中有一个UI Collection View Controller,其中一个操作被分配给一个按钮。这个按钮有它的魔力,然后应该改变标签栏视图到另一个。但是,我无法正确引用选项卡控制器。如何从UICollectionView Cell中引用Tab Bar Controller

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

tabBarController.selectedIndex = 3 

,还可以直接在tabBarController类

tabBarController.goToIndex(3) 

错误说创造一个方法:“goToIndex”的实例成员不能在类型tabBarController

任何使用IDEIA?

谢谢

林有一个小麻烦了解你的引用是正确的意思,但希望这会有所帮助。假设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上的目标操作,每次在单元格内轻按按钮时调用视图控制器上的函数。

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 
    } 
} 
+0

感谢Kuhncj,它在我在TabBarController的UIViewController'child'时有效。试图解释更好的我的疑问,这里是我的结构: TabBarController - > UIViewController嵌入导航控制器 - > UiCollectionView - > ReUsableCell - >按钮 而问题是:我仍然无法更改选项卡索引从在按下按钮时在ReUsable Cell类中。我知道我可以通过协议做到这一点,并调用直接管理UIColelctionView的UIViewController中的函数,但我想知道是否有方法通过ReUsableCell类直接更改它。 – guarinex

+0

没有办法直接在重用单元上做这是一个很好的做法。我用一些额外的反馈更新了我的答案,这可能会帮助你更接近实现目标,但最终你可能会想要坚持代表团或目标行动 – kuhncj

+0

明白了。超级感谢,kuhncj。我想到这是可能的,我无法弄清楚。您的解决方案是要走的路。 – guarinex