Different colors for TabBar items in Tab Bar Controller

自闭症网瘾萝莉.ら 提交于 2020-01-28 02:58:27

问题


I have Tab Bar Controller with few tabs.

  • All tab items should have same non-selected color for image and text.

  • All tab items should have different selected color for image and text.

I am ready to create images with colors needed for selected and non-selected items. And I know how to change this colors for all tabs from AppDelegate

    UITabBar.appearance().tintColor = UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColorFromRGB(rgbValue: MY_COLOR, aplhaValue: 1.0)], for: UIControlState.selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.normal)

But I want to make different colors for different items.


回答1:


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:



来源:https://stackoverflow.com/questions/43002013/different-colors-for-tabbar-items-in-tab-bar-controller

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