简体   繁体   中英

loading viewDidLoad at second xib issue

I have two xib files. I start with "ViewController.xib" and when the user clicks a button it loads a different xib file named "GamePage.xib".

The code of the button is:

-(IBAction)startButtonClicked{    
    UIViewController *gamePage = [[UIViewController alloc] initWithNibName:@"GamePage" bundle:nil];
    [self presentViewController:gamePage animated:NO completion:nil];
}

When the button is clicked, the second xib is shown on screen, but its "viewDidLoad" method don't run…

Why is that?

UIViewController *gamePage = [[UIViewController alloc] initWithNibName:@"GamePage" bundle:nil];

This does not seem correct.

viewDidLoad is probably running but it is viewDidLoad of Apple's UIViewController . You should use your class instead of UIViewController when you initialize it. In general you should use the class which viewDidLoad you need called.

Your XIB must have its Owner. You need to create a class derived from UIViewController and then you need to make that class owner of your XIB. Just follow these steps:

  • Open you project
  • Select the Project Name in the Left Navigation Panel
  • Right Click and select New File
  • Select Objective C Type Class
  • When you click on it, it will ask you to give it a name
  • Suppose you gave GameViewController
  • Check the "With XIB for Interface"
  • and then add the files
  • Now in your Navigation Panel you will see three classes GameViewController.h GameViewController.m GameViewController.xib Create your interfaces in your xib.

And now if you have to move to this class and show its view, write the following code:

 -(IBAction)startButtonClicked{    
    GameViewController *gamePage = [[GameViewController alloc] initWithNibName:@"GameViewController" bundle:nil];
    [[self navigationController] pushVIewController:gamePage animated:YES];
    [gamePage release]; //If not used ARC
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM