0

I have 2 ViewControllers that I use App delegate to switch them according to user interaction.

in AppDelegate.m I have:

    - (void) switchViews
{
    if (_viewController.view.superview == nil) {
        [_window addSubview:_viewController.view];
        [_window bringSubviewToFront:_viewController.view];
        [viewController2.view removeFromSuperview];
    } else
    {
        [_window addSubview:_viewController2.view];
        [_window bringSubviewToFront:_viewController2.view];

        [_viewController.view removeFromSuperview];
    } 
}

_viewController is for main view and _viewController2 is for glview(I am using isgl3d). The switch works but everytime I switch back to glview, I see duplicated view on top, which I suspect even main view is duplicated too.

Any idea how can I remove the view entirely so that I don't have this issue? Thanks!

sooon
  • 4,718
  • 8
  • 63
  • 116

2 Answers2

2

You shouldn't be adding and removing the views like this, just change which controller is the root view controller of the window. Doing that make the new controller's view a subview of the window, and removes the old controller's view.

if ([self.window.rootViewController isEqual: _viewController]) {
    self.window.rootViewController = viewController2;
}else{
    self.window.rootViewController = viewController;
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Thanks! rdelmar. Your method works. But I have to find another way to addsubview. If I add both subview in applicationDidFinishLaunching, both view are running eventhough only a view is on screen. – sooon Apr 15 '13 at 17:23
  • @sooon, I don't understand your comment. What do you mean, "both views are running"? – rdelmar Apr 15 '13 at 19:45
  • Maybe my question is when should I instantiate the viewController2? What I currently do is I instantiate both VCs in AppDelegate's "applicationDidFinishLaunching". – sooon Apr 16 '13 at 01:57
  • @sooon, it depends on when you want it. There's no reason to instantiate it until you're ready to switch to it. – rdelmar Apr 16 '13 at 02:02
0

I found out how to do this after watching Stanford Coding Together:IOS.

Some critical info of VC that I am not aware of: Everytime VC is instantiate, viewDidLoad is called once to setup all the important stuff like outlets and such. Then viewWillAppear and viewWillDisappear will be called for in between view swapping. Because it is called just a moment before view is shown to user, all the geometry setting like view orientation and size is set here.

so what I do is: I addSubview in viewDidLoad, the do all the running setup in viewWillappear and viewWillDisappear.

one more note: view will remain there as long as the app still running.

anyway Thanks rdelmar for helping.

sooon
  • 4,718
  • 8
  • 63
  • 116