快速更改标签栏非选定图标颜色

jod*_*oda 5 uitabbarcontroller swift

我有标签栏,我想将图标颜色从默认灰色更改为白色,我在 AppDelegate 中添加了这一行

UITabBar.appearance().barTintColor = UIColor(red:0.51, green:0.39, blue:0.37, alpha:1.0)
Run Code Online (Sandbox Code Playgroud)

这是更改selected项目,我如何在未选择的情况下执行此操作?

Ana*_*mje 1

根据标签栏控制器的以下代码进行更改,以更改选定的选项卡项目和取消选定的颜色。

class TabbarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UITabBar.appearance().tintColor = UIColor.purpleColor()

        // set red as selected background color
        let numberOfItems = CGFloat(tabBar.items!.count)
        let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
        tabBar.selectionIndicatorImage = UIImage.imageWithColor(UIColor.lightTextColor().colorWithAlphaComponent(0.5), size: tabBarItemSize).resizableImageWithCapInsets(UIEdgeInsetsZero)

        // remove default border
        tabBar.frame.size.width = self.view.frame.width + 4
        tabBar.frame.origin.x = -2

    }

    override func viewWillAppear(animated: Bool) {
        // For Images
        let firstViewController:UIViewController = NotificationVC()
        // The following statement is what you need
        let customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "notification@2x")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "notification_sel@2x"))
        firstViewController.tabBarItem = customTabBarItem

        for item in self.tabBar.items! {
            let unselectedItem = [NSForegroundColorAttributeName: UIColor.whiteColor()]
            let selectedItem = [NSForegroundColorAttributeName: UIColor.purpleColor()]

            item.setTitleTextAttributes(unselectedItem, forState: .Normal)
            item.setTitleTextAttributes(selectedItem, forState: .Selected)
        }
    } 
}

extension UIImage {
    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}
Run Code Online (Sandbox Code Playgroud)