Tutorial :How to load subview from the main view?



Question:

I am very new to Obj-C and learning iphone development. My question is how to add subview from app delegate. Lets say I added subview called "MainView" from "applicationDidFinishLaunching" method.

- (void)applicationDidFinishLaunching:(UIApplication *)application {        MainViewController *aViewController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];  self.mainViewController = aViewController;  [aViewController release];    [window addSubview:mainViewController.view];  // Override point for customization after application launch  [window makeKeyAndVisible];  

}

"MainView.xib" file has a button to show its child view. When the button is clicked, it calls "showChildView" method.

- (IBAction)showChildView:(id)sender {      if (self.childViewController == nil) {          ChildViewController *childController = [[ChildViewController alloc] initWithNibName:@"ChildView" bundle:nil];          self.childViewController = childController;          [childController release];      }        [self.view insertSubview:childViewController.view atIndex:0];  }  

From this code, when app launches, it shows "MainView" with a button. But when I clicked the button, the button is still visible as well as the content from the "ChildView.xib" file too.

How can I hide the "MainView" when I pressed the button and show only the contents of the "ChildView"?

Thanks for your help in advance.


Solution:1

well, you have to remove the original view first, before inserting the new subview, do it this way

- (IBAction)showChildView:(id)sender {      if (self.childViewController == nil) {          ChildViewController *childController = [[ChildViewController alloc] initWithNibName:@"ChildView" bundle:nil];          self.childViewController             = childController;          [childController release];      }      [self.mainViewControlle.view removeFromSuperView];      [self.view insertSubview:childViewController.view atIndex:0];  }  

Hope this helps.


Solution:2

You might want to check out the Utility App sample -- it demonstrates switching between two views with animation and adding/removing views from parent views.


Solution:3

you might want to create a navigation controller in the main view and than push the childviewcontroller onto it when invoking showChildView. You'll get the back navigation button for free that way


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »