add ViewController to another ViewController
In this article, let VC as ViewController
will output
- create
- base VC
- sub VC
- add
- sub VC to base VC
create base VC
In this article base VC is
TopViewController(.h | .m)
Main.storyboard
Main.storyboard
TopViewController.h
#import <UIKit/UIKit.h> @interface TopViewController : UIViewController @end
TopViewController.m
#import "TopViewController.h" @interface TopViewController () @property (nonatomic) KeyViewController *keyVC; @end @implementation TopViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }
create sub VC
In this article sub VC is
KeyViewController(.h | .m | .xib)
KeyViewController.xib
KeyViewController.h
#import <UIKit/UIKit.h> @interface KeyViewController : UIViewController +(instancetype) create; @end
KeyViewController.m
#import "KeyViewController.h" @interface KeyViewController () @end @implementation KeyViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } + (instancetype)create { KeyViewController *viewController = [[KeyViewController alloc] initWithNibName:@"KeyViewController" bundle:nil]; return viewController; } @end
add sub VC to base VC
TopViewController.m
#import "TopViewController.h" #import "KeyViewController.h" @interface TopViewController () @property (nonatomic) KeyViewController *keyVC; @end @implementation TopViewController - (void)viewDidLoad { [super viewDidLoad]; [self initKey]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void) initKey { CGFloat width = self.view.bounds.size.width; CGFloat height = self.view.bounds.size.height; // initialization _keyVC = [KeyViewController create]; [self addChildViewController:_keyVC]; // subview placement [self.view addSubview:_keyVC.view]; _keyVC.view.frame = CGRectMake(0, 100, width, height); // notice parent to finish append child ViewController [_keyVC didMoveToParentViewController:self]; } @end
reference
very thanks for your knowledge sharing