林有一個小麻煩了解你的引用是正確的意思,但希望這會有所幫助。假設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
}
}
感謝Kuhncj,它在我在TabBarController的UIViewController'child'時有效。試圖解釋更好的我的疑問,這裏是我的結構: TabBarController - > UIViewController嵌入導航控制器 - > UiCollectionView - > ReUsableCell - >按鈕 而問題是:我仍然無法更改選項卡索引從在按下按鈕時在ReUsable Cell類中。我知道我可以通過協議做到這一點,並調用直接管理UIColelctionView的UIViewController中的函數,但我想知道是否有方法通過ReUsableCell類直接更改它。 – guarinex
沒有辦法直接在重用單元上做這是一個很好的做法。我用一些額外的反饋更新了我的答案,這可能會幫助你更接近實現目標,但最終你可能會想要堅持代表團或目標行動 – kuhncj
明白了。超級感謝,kuhncj。我想到這是可能的,我無法弄清楚。您的解決方案是要走的路。 – guarinex