How do I make an action in one view close itself and open another view?

907 views Asked by At

New to obj-c and cocoa, working a on a simple game as my first (mac os x) app. I have a menu view and a game view:

MenuView.h/m
MenuViewController.h/m
GameView.h/m
GameViewController.h/m

I want the menu to be displayed by default, and when the play button (which is in the MenuView) is clicked I want the menu to go away and the game to appear. I understand actions and outlets, but I don't know where to start on making the views swap themselves out. Any help? It seems like I would need to somehow make my MenuViewController talk to my MainController?

3

There are 3 answers

1
Rafael Afonso On BEST ANSWER

Peter Hosey,

If you are looking at the MenuViewController as a sort of "main" view controller, at the moment the play button is clicked, you could initialize an instance of GameViewController:

- (IBAction)gameButtonClicked {

     GameViewController *game = [[GameViewController alloc] init];

     // we put the game view as the MenuViewController's view
     [self setView:game.view];
     [game release];

}

Of course, you need to import the "GameViewController.h" to access it.

4
Peter Hosey On

If you want them in the same window and at the same size, you can put both views into a tabless tab view. Just switch the tab to switch which view is visible.

Another way would be to put them in different windows and use a window controller rather than a view controller for each one. Among other things, this makes it easy to make the game window user-resizable without disturbing the size of the menu window.

0
Nicholas1024 On

Since you want your MenuViewController to be what calls and takes care of GameViewController, I'd suggest something similar to what Rafael said. Try putting an instance of GameViewController in your Interface Builder file, but making it hidden. When they press the "Play" button to activate the game, simply send the GameViewController to the front and make it visible. It's a bit clumsy, but it works. Remember to hide all the buttons and interactions regarding your menu though. You don't want to accidentally activate the high scores list when playing a game!

Also, I'd recommend looking into Utility applications. (They're one of the template types you're given when you create a new project.) They're built to switch between two seperate view controllers, and it might just be what you're looking for.