crazyoxygen
crazyoxygen

Reputation: 716

Why can't I use pushViewController with UIButton?

I want to use pushViewController but I can't. I remember that I can use this code in xcode3.

Here is code in IBAction Button

-(IBAction)changtoCal:(id)sender
{
    NSLog(@"get in");
    UINavigationController *cal_nav = [[UINavigationController alloc] initWithNibName:@"calculator" bundle:nil];
    [self.navigationController pushViewController:cal_nav animated:YES];
}

It don't push. Why ??? Could you tell me and how can I push it ???

And here is my AppDelegate .h

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    UINavigationController *navigationController;
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@property (strong, nonatomic) IBOutlet UINavigationController *navigationController;

@end

.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [_window addSubview:[navigationController view]];
    [self.window makeKeyAndVisible];
    return YES;
}

Upvotes: 1

Views: 1981

Answers (2)

beryllium
beryllium

Reputation: 29767

You should create instance of your custom UIViewController in IBAction, not an new UINavigationController

// change UICalculatorViewController to your view controller
UICalculatorViewController *cal_nav = [[UICalculatorViewController alloc] initWithNibName:@"calculator" bundle:nil];
[self.navigationController pushViewController:cal_nav animated:YES];

Upvotes: 2

Felix Lamouroux
Felix Lamouroux

Reputation: 7494

I would guess that the UIViewController is not correctly embedded in the UINavigationController. That would mean that self.navigationController = nil.

I do not know the XIB, but you could fix it by doing the following:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = navc;
    [_window addSubview:navc.view];
    [self.window makeKeyAndVisible];
    return YES;
}

Upvotes: 1

Related Questions