1

I use below code for get selected items of tab bar controller. My UITabbar has 7 view controllers(there are 3 items in More tab). this code work only for 5 tabs but it don`t return selected index of items on More!

import UIKit
class CustomTabbarController: UITabBarController{

  override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
  }

  override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print(self.selectedIndex)
  }
}

2 Answers2

1

Following code worked for me. I had to redesign moreTableView to follow my app design. Function 'didSelectRowAt' returns what index is selected.

This code is added to 'UITabBarController' class.

var moreTableView: UITableView?
weak var currentTableViewDelegate: UITableViewDelegate?

func customizeMoreTableView() {
    moreTableView = moreNavigationController.topViewController?.view as? UITableView
    currentTableViewDelegate = moreTableView?.delegate
    moreTableView?.delegate = self
    moreTableView?.dataSource = self
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (viewControllers?.count ?? 4) - 4
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let moreCell = UITableViewCell()

    let item = viewControllers?[indexPath.row + 4].tabBarItem
    moreCell.textLabel?.text = item?.title
    moreCell.textLabel?.textColor = .white
    moreCell.imageView?.image = item?.image
    moreCell.imageView?.tintColor = .white
    moreCell.backgroundColor = .black

    return moreCell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    currentTableViewDelegate?.tableView!(tableView, didSelectRowAt: indexPath)
}
Arijan
  • 297
  • 3
  • 6
0

Get selected item like this :

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print(tabBar.items?.index(of: item))
}
Vini App
  • 7,339
  • 2
  • 26
  • 43