Search code examples
iosswiftuitabbarcontrolleruitabbaritem

Single tab bar item present different view controllers depending on a condition?


I am making an app that has a couple of different tabs using a tab bar controller. I add items to a bag in the first tab, and update the cart in the next viewcontroller. If the user goes to the second tab (the cart) without adding anything I want it to present a view controller saying the cart is empty. If they go to it once they have added something then it will show a table view.

Is there any way to tell a tab bar controller to present different view controllers depending on a condition?


Solution

  • The simplest option is to use one CartViewController, whose view has two subviews, a table view (A) with the cart items and another view (B) with the 'cart is empty' message.

    Override its viewWillAppear function, and depending on the cart, show view A and hide view B or vice versa.

    You can modify the child view controllers of a UITabBarController, via the viewControllers property. However, doing this by reacting on changes in the cart is complicated an not worth the trouble, IMHO.