简体   繁体   中英

Adding views with controllers to a view with controller - proper way?

I have to add several views (each having own controller) to a main view (with controller). I am following MVC. Should the code to add these subviews be written in view class or controller class? Also, what is proper way,

MyViewController1 *myViewController1 = [[MyViewController1 alloc] init];
[myMainViewController.view addSubview:myViewController1.view];

Or, some other way?

There is another option - container view controller (with addChildViewController method), but that is tough to manage, so I need the simple way.

If you're adding view controllers to the view of another view controller, then you need to use container containment. You can do that in IB with container views. That makes it easier, than making custom container controllers in code.

The Absolute best way is to maintain ViewControllers according to their functionality (ex. one might be dashboardView one might be settingsView ). Now when moving from one view controller to another is to use navigationController .

The practice I follow is to declare one navigationController in appDelegate when your app starts and then keep reusing this. Example -

YourAppDelegate *delegate=(YourAppDelegate *)[[UIApplication sharedApplication] delegate];
MyViewController1 *myVC = [[ FLOHome alloc ]initWithNibName:@"MyViewController1" bundle:[NSBundle mainBundle]];
[delegate.navigationController pushViewController:myVC animated:NO];

This is the absolute best way when dealing with viewControllers. navigationController handles whole lot of stuff like memory management, caching views to make them snappy. You could keep pushing viewcontrollers and poping them when you exit from them...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM