Search code examples
swiftuitabbarcontrolleruitabbaruitabbaritem

Two color items on Tab Bar, Swift


Is is possible to set an item with two colors on the tab bar?

(I'm a beginner in swift)

What I want to achieve:

I want to have something-like a white background for each item in both active and inactive states.

-> Example of what I want


What I have tried so far:

I've been trying by using a png with transparency, white color and black color but it seems that anyhing that is not a transparent pixel is taken as the same color. (The asset I've working with is rendered as a whole color image instead of differentiating black and white)

-> The asset I thought it would work


What I think its the way but don't know how:

(This is an assumption)

I think this could be done by setting an inactive item in the background (first layer, white color) and an active item (second layer, black color) in the same coordinates with the color I want to change:

-> Two assets for Layer 1 and layer 2


I'm using an storyboard with storyboard references to set initial configuration for the assets of both active an inactive states.

I'm setting active state color programatically.

Suggestions to achive this in more elegant ways are welcome.

Thank you :)


Solution

  • Thank you all for your help.

    Inspired by @Jake link, I kept searching and found that Xcode has different modes to render image assets.

    Render as Template:

    The default one, renders images as they were templates. (You can take any image and colorize it programatically, but it does not recognice if it has more than 1 color)

    Render as Original:

    The other mode, renders images as they are. So it actually recognizes if it has more than 1 color and leave them that way. This allows you to have tab bar items with multiple colors.


    How can this property be modified?

    Programatically:

    (as a property)

    tabBarItem.image = tabBarImage.withRenderingMode(.alwaysOriginal)
    
    //or
    
    tabBarItem.image = tabBarImage.withRenderingMode(.alwaysTemplate)
    

    Via Interface Builder:

    1. Assets Folder, 2. Select an asset, 3. Attribute Inspector

    Render as: Default, Original Image, Template Image.