Default tab bar item colors using swift Xcode 6

Each (default) tab bar item consists of text and icon. It is pretty easy to change the text colors globally by specifying the appearance:

// you can add this code to you AppDelegate application:didFinishLaunchingWithOptions: 
// or add it to viewDidLoad method of your TabBarController class
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)

With images situation is a little bit more complicated. You cannot define their appearance globally. You should redefine them in your TabBarController class. Add code bellow to viewDidLoad method of your TabBarController class:

for item in self.tabBar.items as [UITabBarItem] {
    if let image = item.image {
        item.image = image.imageWithColor(UIColor.yellowColor()).imageWithRenderingMode(.AlwaysOriginal)
    }
}

As we know there is no imageWithColor(...) method in UIImage class. So here is the extension implementation:

// Add anywhere in your app
extension UIImage {
    func imageWithColor(tintColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)

        let context = UIGraphicsGetCurrentContext() as CGContextRef
        CGContextTranslateCTM(context, 0, self.size.height)
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, .Normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context, rect, self.CGImage)
        tintColor.setFill()
        CGContextFillRect(context, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

imageWithColor was borrowed from this answer: https://stackoverflow.com/a/24545102/3050466

Leave a Comment