默认情况下,TabBar上的选定项目未突出显示

时间:2019-06-13 12:31:06

标签: swift xcode tabbarcontroller

我正在使用带有两个项目的TabBar。我正在.xib文件上创建它,并以编程方式设置ViewControllers。我可以通过以下方式选择默认的VC:

    selectedIndex = 0

现在的问题是tabBar没有突出显示所选项目图标。

我在TabBarController的viewDidLoad()上设置了VC:

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

下面是在每个VC上创建项目的代码:

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

默认情况下,不仅选中的索引没有突出显示,有时它只显示其中一个,直到我点击tabBar。

编辑:

我添加了三张图片。

第一个是在加载VC之后立即进行的。没有点击任何项目,以编程方式选择了索引0,并且VC如期出现。

第二是在第二个项目上点击后显示的,但两个都没有突出显示。

第三次是在再次轻按一次之后,现在,无论按下哪一个,突出显示都有效。

enter image description here

enter image description here

enter image description here

编辑2:

我添加了一个视频:

HERE

2 个答案:

答案 0 :(得分:1)

您必须像下面一样将图像分配给selectedIndex tabBar项目

  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"

答案 1 :(得分:1)

只需将图像和所选图像设置为tabBarItem,请参见以下代码。

  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"

    for tabBarItem in tabBar.items! {
        tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
    }