Lets say that I have 4 view controllers (call them FirstView,SecondView,ThirdView,FourthView) which are created programmatically and all are in separate files:
In AppDelegate.m didFinishLaunchingWithOptions method I have these lines of code
self.rootViewController = [[rootViewController alloc]initWithNibName:@"rootViewController" bundle:nil];
self.window.rootViewController = self.rootViewController;
In rootViewController.m loadview method I have
self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
self.firstView = [[FirstView alloc]init];
[self.view addSubview:self.firstView.view];
That code works fine – first view is displayed.
Let’s continue
In FirstView.m switchViews method
NOTE: Please see the comments in code
self.secondView = [[SecondView alloc] initWithNibName:@"SecondView" bundle:nil];
// I think here secondView is added to rootViewController - right ?
[self.view.superview addSubview:self.secondView.view];
// Here first view is removed from rootViewController - right ?
[self.view removeFromSuperview];
Here is how I add/remove views.
Is this approach correct?
Can you recommend a better solution?
I have read about UINavigationController, but I don’t think it could be a solution in this case.
You say:
Then you say:
Which makes me think that
FirstViewisn’t actually aUIView– as you claim it is. Instead, it’s probably aUIViewController– a different beast altogether.If my suspicion is correct – then you are “off-track” so to speak.
Going beyond that to your sample code snippet:
This is definitely not a great idea. Here’s why:
First: your view controller doesn’t explicitly “know” anything about the superview you are so casually inserting and removing subviews to/from – so it shouldn’t do that. You may, alternatively, create your own view and insert/remove subviews from that – which would not only be perfectly acceptable but also common practice.
Second: if these are actually
UIViewControllers like I think they are – then you are not properly handling hooking them up to theUIViewControllerevent chain – which means methods on these subclasses likeviewDidAppear:orviewDidUnloadwill not fire.