Question

I am programmatically changing the tab bar item for my tab bar at runtime. The whole UI of my app uses Storyboards and this is the only area where I am making the UI changes in code.

So, the UI changes depending on a property. If this property cannot be found, the array of viewControllers changes to the new array that contains the new UIView.

Here's my code for the TabBarController.m:

NSArray *arrayOfControllers = self.viewControllers;
NSMutableArray *newArrayOfControllers = [[NSMutableArray alloc]init];

for (id controller in arrayOfControllers)
{
    [newArrayOfControllers addObject:controller];
}


if ( !isMember)
{
    NotMemberVC *vc = [[NotMemberVC alloc]init];
    vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Test" image:[UIImage imageNamed:@"door-sign.png"] tag:0];

    [newArrayOfControllers removeLastObject];
    [newArrayOfControllers addObject:vc];

    self.viewControllers = newArrayOfControllers;
}

And here's what it looks like when I select this new tab bar item: enter image description here

Any suggestions as to how I can fix this?

Was it helpful?

Solution

First of all you don't need to do a for cycle when you have a method to do a mutableCopy of the array:

NSArray *arrayOfControllers = self.viewControllers;
NSMutableArray *newArrayOfControllers = [arrayOfControllers mutableCopy];

then here, you was not initializating the viewController with the view. In this case you have your VC with the UIView in your storyboard, and so you have to choose a StoryboardID in your VC in the Storyboard, and then:

if ( !isMember)
{
    NotMemberVC *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Your_Identifier_ViewController_Storyboard"];

    vc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Test" image:[UIImage imageNamed:@"door-sign.png"] tag:0];

    [newArrayOfControllers removeLastObject];
    [newArrayOfControllers addObject:vc];

    //Here make a copy to come back to immutable array
    self.viewControllers = [newArrayOfControllers copy];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top