Different colors for TabBar items in Tab Bar Controller

妖精的绣舞 提交于 2019-11-28 14:48:39

In your Storyboard select your TabBarController and give it a custom class: TabBarController in this example:

And then create the custom TabBarController file:

//  Copyright © 2017 Erick Vavretchek. All rights reserved.

import UIKit

class TabBarController: UITabBarController {

  enum tabBarMenu: Int {
    case home
    case list
    case settings
  }

  // MARK: UITabBarController

  override func viewDidLoad() {

    super.viewDidLoad()

    guard let tabBarMenuItem = tabBarMenu(rawValue: 0) else { return }
    setTintColor(forMenuItem: tabBarMenuItem)
  }

  override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    guard
      let menuItemSelected = tabBar.items?.index(of: item),
      let tabBarMenuItem = tabBarMenu(rawValue: menuItemSelected)
      else { return }

    setTintColor(forMenuItem: tabBarMenuItem)
  }

  // MARK: Private

  private func setTintColor(forMenuItem tabBarMenuItem: tabBarMenu) {
    switch tabBarMenuItem {
    case .home:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.green
    case .list:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    case .settings:
      viewControllers?[tabBarMenuItem.rawValue].tabBarController?.tabBar.tintColor = UIColor.red
    }
  }
}

It is also important that in your Assets.xcassets folder you select the each image you are using for your TabBarItem and set them to Render As: Template Image. That's how you can simply change its tintColor to whatever you like:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!