Harish
Harish

Reputation: 1408

Set multicolor tab bar icon instead of monochrome icon

I need a way to have multicolor tab bar icons, but for some reason, iOS keeps drawing the icon in a monochrome fashion.

I tried various methods such as including this line of code: tabBarItem.image = #imageLiteral(resourceName:"routineIcon").withRenderingMode(.alwaysOriginal) in the viewDidLoad of my first view controller but I had no luck.

Is there any way I can retain color information in a tab bar icon without making it monochrome? It looks a thousand times better when it's multicolored.

Thanks,

Harish

Upvotes: 2

Views: 872

Answers (1)

deadbeef
deadbeef

Reputation: 5563

You need to create a new UITabBarItem and assign it to the tabBarItem property of your view controller.

// In viewDidLoad()
self.tabBarItem = UITabBarItem(title: "Hello world!", image: #imageLiteral(resourceName: "routineIcon").withRenderingMode(.alwaysOriginal), tag: 0)

Also, if you're using an assets catalog (which you should), notice that in your asset settings you have a Render As setting which you can set to Always Original. You can then ommit the .withRenderingMode(.alwaysOriginal) when using your image.

// In viewDidLoad()
self.tabBarItem = UITabBarItem(title: "Hello world!", image: #imageLiteral(resourceName: "routineIcon"), tag: 0)

There is also an initializer that takes a selected image if you have one

// In viewDidLoad()
self.tabBarItem = UITabBarItem(title: "Hello world!", image: #imageLiteral(resourceName: "routineIcon"), selectedImage: #imageLiteral(resourceName: "routineIconSelected"))

Note : As a general rule, modifying system UIBarItem objects (UITabBarItem for tab bars and UIBarButtonItem for navigation bars or tool bars) often doesn't work and you need to create a new one.
System bar items are the one created with init(tabBarSystemItem:tag:) (for UITabBarItem) or init(barButtonSystemItem:target:action:) (for UIBarButtonItem).
When using a storyboard, you can decide to use either a system bar item or a custom one.

Upvotes: 4

Related Questions