0

I have a TabBar item that is a shopping cart outline called "cart". This is a default icon provided by XCode. With the tab of a button, I want to change this icon to another default icon provided by XCode called "cart.fill"

shoppingCartIcon.image = UIImage(named: "cart.fill")

I already tried the above however this didn't work. Is there an easy solution that I am overlooking?

Anjali Shah
  • 720
  • 7
  • 21
helloworld12345
  • 176
  • 1
  • 4
  • 22
  • see this for help : [how to programmatically change the tabbarItem's image](https://stackoverflow.com/questions/8847483/how-to-programmatically-change-the-tabbaritems-image) – Anbu.Karthik Mar 02 '20 at 04:27

1 Answers1

0

You can do all the customization within this class related to tabbar. Just assign this class TabbarViewController to your UITabbarController in storyboard and customize all images and title accordingly.

class TabbarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let arrayOfImageNameForUnselectedState = ["home_unselected","info_unselected","puzzle","video","more"]

        let arrayOfImageNameForSelectedState = ["home_selected","info_selected"]

        let titlesArray = ["Home","About Us"]

        // Do any additional setup after loading the view.

        if let count = self.tabBar.items?.count {
            for i in 0...(count-1) {
                let imageNameForSelectedState   = arrayOfImageNameForSelectedState[i]
                let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]


                self.tabBar.items?[i].title = titlesArray[i]

                self.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState )?.withRenderingMode(.alwaysOriginal)
                self.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState )?.withRenderingMode(.alwaysOriginal)
            }
        }



        let selectedColor   = UIColor(red: 233.0/255.0, green: 41.0/255.0, blue: 47.0/255.0, alpha: 1.0)
        let unselectedColor = UIColor(red: 127.0/255.0, green: 140.0/255.0, blue: 141.0/255.0, alpha: 1.0)

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: unselectedColor], for: .normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: selectedColor], for: .selected)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
Muhammad Afzal
  • 201
  • 1
  • 9