4

I am trying to set the items for my Tab Bar from the TabBarViewController.

However, once I set the items, here's the error I get:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Directly modifying a tab bar managed by a tab bar controller is not allowed.'

Here's the code:

func imageWithImageSize(image:UIImage , newSize:CGSize) -> UIImage{

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
        image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage

    }



    let image1 = imageWithImageSize(UIImage(named: "Home.png")!, newSize: CGSizeMake(30, 30))

    let homeItem = UITabBarItem(title: "Home", image: image1, selectedImage: image1)


    let image2 = imageWithImageSize(UIImage(named: "Profile.png")!, newSize: CGSizeMake(30, 30))
    let profileItem = UITabBarItem(title: "Profile", image: image2, selectedImage: image2)


    self.tabBar.setItems([homeItem,profileItem, homeItem, homeItem], animated: false)

Is there a solution around it?

dpstart
  • 1,018
  • 1
  • 10
  • 25

1 Answers1

2

you cant modify them directly instead you can do the following things.

1.Get the UITabBarController in which you want to add tabs.suppose you have tabBarController with name tabController.

2.Get all the viewController of tabController.

 guard var viewControllers = tabController.viewControllers else {
      return
    }

3.get your view controller. for ex. we take exampleVC.

4.create tabBarItem for exampleVC

let performanceTabItem = UITabBarItem(title: "example", image: "tabImage", selectedImage: "selectedTabImage" )

5.set

exampleVC.tabBarItem = performanceTabItem

6.append exampleVC with viewControllers

viewControllers.append(exampleVC)

7.set viewControllers of UITabBarController.

tabController.viewControllers = viewControllers
Surjeet Rajput
  • 1,251
  • 17
  • 24