Confused
Confused

Reputation: 3926

Pushing a UIViewController from another UIViewController - How to?

I have a UIViewController subclass(Say BBB) that inherited from already written custom UIViewController class(Say AAA). The BBB class have a UITableView in it and when the user tap on any cell of the UITableView, I want to push another UIViewController class(Say CCC).

So, I tried to push the CCC controller in BBB's tableView: didSelectRowAtIndexPath: method.

My code is,

CCC *ccc = [[CCC alloc] init];
[self.navigationController pushViewController:ccc animated:YES];
[ccc release];

Nothing happens when tapping the cell, so I checked the naviagtion controller of class BBB by the following code.

if (self.navigationController == nil)
{
    NSLog(@"Navigation controller is nil");
}

The message was printed successfully :) So, I tried to assign some thing to navigation controller and my bad luck, it is a read-only property.

Then I tried to make a local UINavigationController by assigning ccc as it rootviewcontroller and then tried to push that local navigation controller. It throws an exception "Pushing the same view controller instance more than once is not supported".

My questions are,

Thanks

Upvotes: 1

Views: 1232

Answers (2)

bert
bert

Reputation: 1596

Put this into your app delegate and the first version of your code should work.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    AAA *aaa = [[AAA alloc] init];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController: aaa];
    [self.window makeKeyAndVisible];

    return YES;
}

Upvotes: 1

cscott530
cscott530

Reputation: 1708

To get the self.navigationController property to be properly set, you'll have to create a UINavigationController with [[UINavigationController alloc] initWithRootViewController: aaa]. Then wherever you're adding aaa currently (a splitViewController, or to the UIWindow, etc.), instead use the navigation controller you create.

For example, if you're setting up the views using code, in your app delegate:

AAA *aaa = [[AAA alloc] init];
UINavigationController *root = [[UINavigationController alloc] initWithRootViewController: aaa];
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[window makeKeyAndVisible];
window.rootViewController = root;

Now, aaa.navigationController will point to root, and so you can do what you had in your original post: [self.navigationController pushViewController: bbb animated: YES];

Upvotes: 0

Related Questions