Search code examples
swiftuitabbarcontrollertabbaruitabbaritem

Change tabBarItem image programmatically


Using iOS14.0.1, Swift5.3, Xcode12.0.1,

I would like to dynamically change the image of a UITabBarController's tabBarItem

Here is my code:

self.tabBarCtrl?.viewControllers?[2].tabBarItem.image = #imageLiteral(resourceName: "Sign_ready")
self.tabBarCtrl?.viewControllers?[2].tabBarItem.selectedImage = #imageLiteral(resourceName: "Sign_ready")

However, in my App, there are two problems

a) The image does change but is way too large b) The color of the image is wrong

How can I get rid of the two problems ?

Here a screenshot of how it currently looks with the code above:

enter image description here


Solution

    1. About The Size You can change the size Image preview check the size (pixels) of the other two images and use the same size enter image description here you can set your images sizewise as in this image
    1. Image Color

    a. First set your image to be always template

    firstviewcontrolle.tabBarItem.image = UIImage(named: "database copy")?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)

    b. Secondly use this code to set the tint color

    UITabBar.appearance().unselectedItemTintColor = UIColor.black