10

I have a tab bar based application in which I am trying to add tab bar items to the tab bar dynamically using setItems method of the UITabBar.

Here is the code:

[self.tabBarController.tabBar setItems:self.level1TabBarItems animated:YES];

Where self.level1TabBarItems is an NSMutableArray with 4 UITabBarItems in it. When I run this code, I get an exception from the compiler.

NSInternalInconsistencyException, reason:Directly modifying a tab bar managed by a tab bar controller is not allowed.

I have tried deleting the UITabBarViewController and adding it again but it did not work.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Aqueel
  • 1,246
  • 3
  • 23
  • 46

3 Answers3

17

The documentation clearly states that you shouldn't modify the tab bar directly. Use setViewControllers:animated: instead.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
12

I hope can help you with following code:

func application(_application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = LongUITabBarController()
    window?.makeKeyAndVisible()

    return true
}
import UIKit


class LongUITabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let vc1 = VC1_ViewController()
        let vc2 = VC2_ViewController()
        let vc3 = VC3_ViewController()
        let vc4 = VC4_ViewController()

        vc1.tabBarItem = UITabBarItem(title: "LIST ALL", image: UIImage(named: "list"), tag: 1)
        vc2.tabBarItem = UITabBarItem(title: "BEST CELLER", image: UIImage(named: "bestCeller"), tag: 2)
        vc3.tabBarItem = UITabBarItem(title: "MOST LIKE", image: UIImage(named: "like"), tag: 3)
        vc4.tabBarItem = UITabBarItem(title: "NEW", image: UIImage(named: "new"), tag: 4)

        viewControllers = [vc1, vc2, vc3, vc4]
        setViewControllers(viewControllers, animated: true)

        // backGround for tapBarView
        tabBar.barTintColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)

    }


}
KernelPanic
  • 2,328
  • 7
  • 47
  • 90
user7352457
  • 121
  • 1
  • 2
1

AFAIK you can't replace the tabbar. It's not allowed by Apple. I'll check it now.

What you can do though, is creating a segmentedController and restyle it to look like a tabbar. It has pretty much the same use.

EDIT: Above, ninja poster said it: you can't alternate the tabbar. I'd suggest the segmented controller.

Joetjah
  • 6,292
  • 8
  • 55
  • 90