0

I am using UITabBar, not UITabBarController. Whenever user clicks on any tab, I am able to see the underlined image.

public override func viewDidLoad() {
    super.viewDidLoad()
    UITabBar.appearance().selectionIndicatorImage = getImageWithColorPosition(color: UIColor.darkGray, size: CGSize(width:presenterView.frame.size.width/2, height:49), lineSize: CGSize(width:presenterView.frame.size.width/2, height:2))
}

//getImageWithColorPosition is for adding underlined image below UITabBarItem

func getImageWithColorPosition(color: UIColor, size: CGSize, lineSize: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    let rectLine = CGRect(x: 0, y: size.height-lineSize.height, width: lineSize.width, height: lineSize.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    UIColor.clear.setFill()
    UIRectFill(rect)
    color.setFill()
    UIRectFill(rectLine)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    openItem1()
}

public func  tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if (item.tag == 0) {
        openItem1()
    } else {
        openItem2()
    }
}

However, when user clicks on any of the tab items then only underlined image is displayed. I want to select a default tab when user lands on the screen for the first time. As I am doing it programmatically, the underline image doesn't show up. I read couple of stack overflow posts which say that selection on UITabBar can not be triggered programmatically.

Is there any other way to go about it?

A_G
  • 2,260
  • 3
  • 23
  • 56

1 Answers1

0

If I understand the question correctly, you want to programmatically select a tab on your UITabBar, when the user opens the app. You can do this inside the AppDelegate, for example in didFinishLaunchingWithOptions

In my project I jump to tabs in my tabbar controller depending on events like certain notifications. Inside the AppDelegate I use the following code to programmatically select a tab:

if let tabbarController = self.window?.rootViewController as? UITabBarController {
    tabbarController.selectedIndex = 0
}

Per default the selected item will be the one with index 0 if the app was launched from a cold start and the last opened tab, if the app was in was previously launched and is held in the app switcher.

Hope this is what you are looking for.

erik_m_martens
  • 496
  • 3
  • 8