add ViewController to another ViewController

In this article, let VC as ViewController

will output

f:id:mat5ukawa:20150506014143j:plain

  • 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

f:id:mat5ukawa:20150506013805p:plain

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

f:id:mat5ukawa:20150506013912p:plain

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

developer.apple.com

qiita.com

stackoverflow.com

stackoverflow.com