user677325
user677325

Reputation: 23

IOS load different root of UiNavigationController of TabController

I thought there would be an easy answer to this but I can't seem to find it. I have an IOS app that has a tab bar. You log in and it goes to the tab bar. For one of the tab buttons I would like to display a different root view based on a condition. I created a custom UiNavigationController and I'm set up the following conditional statement.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString *can_post = @"yes" ;
    NSLog(@"can post: %@",can_post);


    if([can_post isEqualToString:@"yes"]) {
        // Display UserCanPostViewController
        NSLog(@"user can post");

    }
    else {
        // Display UserCanNotPostViewController
        NSLog(@"user can not post");
    }

}

The problem is that I can't seem to set the root view. All the examples I've been able to find show how to set the root view under appdelegate which seems to affect the entire app. I just want this conditional for apply for a single tab button.

Thanks for the help!

Upvotes: 0

Views: 32

Answers (1)

DBoyer
DBoyer

Reputation: 3122

In App Delegate...

Set up your tab bar to contain tabs which are navigation controllers for the specific tab you are talking about...

...

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController1];

 [tabBarController setViewControllers:@[navigationController,
                                        viewController2,
                                        viewController3,
                                        viewController4]];

[self.window setRootViewController:tabBarController];

...

Make AppDelegate the UITabBarControllerDelegate and implement the following delegate method.

Note there are cleaner ways of doing this but this will work for now (This isn't really the AppDelegate's job but you can refactor later however you want)

...

    tabBarController.delegate = self

...

In this delegate method....

- (void)tabBarController:(UITabBarController * nonnull)tabBarController
     didSelectViewController:(UIViewController * nonnull)viewController
{
    if (THIS IS NOT THE SPECIFIC TAB) return;

        UINavigationController *navigationController = (UINavigationController *)viewController;

    if([can_post isEqualToString:@"yes"]) {
        // Display UserCanPostViewController
        NSLog(@"user can post");

        [navigationController setViewControllers:@[UserCanPostViewController]];
    }
    else {
        // Display UserCanNotPostViewController
        NSLog(@"user can not post");

        [navigationController setViewControllers:@[UserCanNotPostViewController]];
    }

}

Upvotes: 1

Related Questions