通过正确引用它来理解您的意思有点困难,但希望这会有所帮助。假设 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)
}
基于 cmets 的更新:
您是正确的,除非您将其设置为单元格本身(不推荐)或应用程序委托的属性,否则您无法访问单元格内的 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
}
}