I am starting a multiview app with two views: NewGame and Players. I thought I was setting everything up properly, but apparently not.
MainViewController.h
#import <UIKit/UIKit.h>
@class NewGame; @class Players;
@interface MainViewController : UIViewController {
IBOutlet NewGame *newGameController;
IBOutlet Players *playersController;
}
-(IBAction) loadNewGame:(id)sender;
-(IBAction) loadPlayers:(id)sender;
-(void) clearView;
@end
MainViewController.m
#import "MainViewController.h"
#import "NewGame.h"
#import "Players.h"
@implementation MainViewController
-(IBAction) loadNewGame:(id)sender {
[self clearView];
[self.view insertSubview:newGameController atIndex:0];
}
-(IBAction) loadPlayers:(id)sender {
[self clearView];
[self.view insertSubview:playersController atIndex:0];
}
-(void) clearView {
if (newGameController.view.superview) {
[newGameController.view removeFromSuperview];
} else if (playersController.view.superview) {
[playersController.view removeFromSuperview];
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[self loadNewGame:nil];
[super viewDidLoad];
}
A couple of images…
https://i.stack.imgur.com/GwXMa.png
https://i.stack.imgur.com/XHktH.png
Views are objects that represent what appears on screen. View controllers are objects that perform application logic relating to those views. A view hierarchy is a collection of views. You are attempting to add a view controller to a view hierarchy as if it were actually a view.
Roughly speaking, you should have one view controller for every “screen” of your app. This view controller can manage any number of views. Its main view is accessible through its
viewproperty.A quick fix to get your application operational would be to add the main view of your view controllers instead of the view controllers themselves. So, for example, this:
…would become this:
Having said that, this is not a good solution long-term, and you should investigate a more structured way of organising transitions from view controller to view controller.
UINavigationControlleris a good option for beginners.