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

Selected item by default on TabBar is not getting highlighted

我正在使用带有两个项目的 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。

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

第三个一个是再按一下,现在无论按哪一个,高亮都有效

编辑 2:

我添加了一个视频:

HERE

您必须相应地将图像分配给 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"

只需将图片和选中的图片设置为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)
    }