Ios Developer
Ios Developer

Reputation: 888

To access tabbar from uiview in swift

In my application when I am getting any notification I am showing a customView. And if user touches anywhere on the screen, the view will disappear. I have a UITabBar with four tabs. After getting notification, when I click on the view, the 2nd tab should be selected (I may be anywhere in the app). But I am unable to select the 2nd tab. It always opens the first tab. How do I call the "didSelect item" from this customView? Following is my code. Please verify it and help me to resolve my issue.

My code is:

{
    let storyBoard = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainTabbarView") as? MainTabbarView
    storyBoard?.selectItem(withIndex: 3)  
} 

In my UITabBarController I have wrritten the following code:

func selectItem(withIndex index: Int) {
    if let controller = tabBarController, let tabBar = tabBarController?.tabBar, let items = tabBarController?.tabBar.items {
        guard index < items.count else { return }
        controller.selectedIndex = index
        controller.tabBar(tabBar, didSelect: items[index])
    }
} 

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if let items = tabBar.items {
        items.enumerated().forEach { if $1 == item { print("your index is: \($0)") } }
    }
}

Upvotes: 0

Views: 1730

Answers (1)

Sky Shadow
Sky Shadow

Reputation: 324

Based in your code, you are initializing a new instance of TabBarController instead of using the active one, so it really does not update your current tab bar. You can access a view controller that tabBarController owns. Then from there:

activeViewController.tabBarController.selectedIndex = 1

That should do it.

Upvotes: 1

Related Questions