swiftxcodetabbarcontroller

Selected item by default on TabBar is not getting highlighted


I'm using a TabBar with two items. I'm creating it on a .xib file and setting the ViewControllers programatically. I can choose the default VC with:

    selectedIndex = 0

The problem now is the tabBar not highlighting the selected item icon.

I set the VC's on TabBarController's viewDidLoad():

    let firstViewController = FirstViewController(nibName: "FirstViewController", bundle: nil)
    let secondViewController = SecondViewController(nibName: "SecondViewController", bundle: nil)
    self.viewControllers = [firstViewController, secondViewController]

And here's the code to create the items on each VC:

    let tabBarItem = UITabBarItem(title: "First", image: #imageLiteral(resourceName: "firstImage"), selectedImage: nil)
    self.tabBarItem = tabBarItem

Not just the selected index by default is not highlighting, sometimes It shows only one of them until I tap on the tabBar.

EDIT:

I add three images.

First one is taken just after loading the VC. NO item has been tapped, programatically selected index 0 and VC is presented as expected.

Second one is after performing a tap on the second item, it shows but both are not highlighted.

Third one is after doing one more tap, now, no matter which one is pressed, the highlighting works.

enter image description here

enter image description here

enter image description here

EDIT 2:

I added a video:

HERE


Solution

  • You have to assign the images to selectedIndex tabBar item accordingly like below

      let myTabBarItem1 = (self.tabBar.items?[0])! as UITabBarItem
      myTabBarItem1.image = UIImage(named: "Unselected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
      myTabBarItem1.selectedImage = UIImage(named: "Selected ")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
      myTabBarItem1.title = "First"
    
    
      let myTabBarItem2 = (self.tabBar.items?[1])! as UITabBarItem
      myTabBarItem2.image = UIImage(named: "Unselected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
      myTabBarItem2.selectedImage = UIImage(named: "Selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
      myTabBarItem2.title = "Second"