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



我有一个标签栏控制器应用程序,其中一个选项卡中有一个 UI 集合视图控制器,其中有一个分配给按钮的操作。此按钮发挥其魔力,然后应将选项卡栏视图更改为另一个选项卡栏视图。但是,我无法将其直接引用到选项卡控制器。

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

tabBarController.selectedIndex = 3

并直接在 tabBarController 类中创建方法

tabBarController.goToIndex(3)

错误显示:"goToIndex"的实例成员不能在类型选项卡上使用 BarController

有什么想法吗?

谢谢

我有点难以理解您正确引用它的意思,但希望这会有所帮助。假设 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
}
}

最新更新