2017-07-07 22 views
0

我有一個標籤欄控制器應用程序,在其中一個選項卡中有一個UI Collection View Controller,其中一個操作被分配給一個按鈕。這個按鈕有它的魔力,然後應該改變標籤欄視圖到另一個。但是,我無法正確引用選項卡控制器。如何從UICollectionView Cell中引用Tab Bar Controller

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

tabBarController.selectedIndex = 3 

,還可以直接在tabBarController類

tabBarController.goToIndex(3) 

錯誤說創造一個方法:「goToIndex」的實例成員不能在類型tabBarController

任何使用IDEIA?

謝謝

回答

1

林有一個小麻煩了解你的引用是正確的意思,但希望這會有所幫助。假設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

相關問題