Tolgay Toklar
Tolgay Toklar

Reputation: 4343

Launching segue from tab bar controller

I want to launch segue from tab bar item. When user touches an item on the tab bar. I want to launch a segue.

To do this I writed this code:

class TabBarController: UITabBarController, UITabBarControllerDelegate {

    @IBOutlet var tabs: UITabBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if item.tag == 3 {
            self.performSegueWithIdentifier("test123", sender: self)
        }
    }
}

Actually it works well except a problem. This is launching segue but also switching the tab. I don't want this. It should just launch start segue shouldn't switch the tab.

How can I prevent this problem?

Upvotes: 0

Views: 495

Answers (1)

ilnar_al
ilnar_al

Reputation: 952

Here's the minimal changes to get your code work

in your viewDidLoad() add

self.delegate = self

Then implement delegate method

func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
    let shouldSelectIndex = tabBarController.viewControllers?.indexOf(viewController)
    if shouldSelectIndex == 2
    {
        self.performSegueWithIdentifier("test123", sender: self)
        return false
    }
    return true
}

That should work.

However I think you have design issues.

  1. Subclass as a delegate is strange. Better separate delegate.
  2. Instead of tag/indecies use introspection or another delegation or something

Upvotes: 1

Related Questions