Search code examples
objective-cuiviewviewdidload

How to remove multiple many view from superview


I have some uiview, one call another in this way:

From first uiview:

MyViewController *contr1 = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[self.view addSubview:contr1.view];

From second uiview:

MyViewController2 *contr2 = [[MyViewController2 alloc] initWithNibName:@"MyViewController2" bundle:nil];
[self.view addSubview:contr2.view];

now in the third uiview i want to return back on the first updating it ( calling viewDidLoad ). how can i do?


Solution

  • First of all - you are doing it wrong.

    Since you are using view controllers present them modally or push them:

    MyViewController2 *contr2 = [[MyViewController2 alloc] initWithNibName:@"MyViewController2" bundle:nil];
    [self presentModalViewController:contr2];
    

    If you want to dismiss modal controllers exactly to your root view controller you should obtain a pointer to it in the controller you are currently using and send it a message to dismiss every modal view that there is on it.

    - (IBAction)doHomePage:(id)sender {
      MyAppDelegate *appDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
      [appDelegate.navigationController.rootViewController dismissModalViewControllerAnimated:YES];
    }
    

    Also instead of viewDidLoad: you might want to use viewWillAppear: or viewDidAppear:.

    Sorry beforehand if there are some typo errors in the code since I wrote it by hand.