#import “RootViewController.h”
#import “SecondViewController.h”
@interface RootViewController ()
声明成属性 方便获取
@property (nonatomic,retain)
SecondViewController *secondVC;
@end
@implementation RootViewController
- (void)dealloc
{
[_secondVC release];
[super dealloc];
}
– (void)viewDidLoad {
[super viewDidLoad];
1.首先创建一个继承于UIViewController的类
SecondViewController
2.引入 SecondViewController的头文件
在根视图RootViewController.m 里
添加子控制器
self.secondVC = [[SecondViewController alloc] init];
把secondVC添加成子控制器 让rootVC去管理
[self addChildViewController:self.secondVC];
把secondVC.view 添加到 rootVC.view 上
[self.view addSubview:self.secondVC.view];
释放
[_secondVC release];
self.view.backgroundColor = [UIColor redColor];
添加一个按钮 移除 子控制器
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake(100, 100, 100, 100);
button.backgroundColor = [UIColor blackColor];
把按钮添加到跟视图rootVC.view上 也就是self.view
[self.view addSubview:button];
给按钮添加一个方法删除视图
[button addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
}
实现按钮的方法
– (void)buttonClick:(UIButton *)button
{
移除视图
[self.secondVC.view removeFromSuperview];
移除子控制器
[self.secondVC removeFromParentViewController];
}
视图生命周期
添加子视图时先发生
视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@”视图将要出现”);
}
添加子视图时后发生
视图已经出现
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@”视图已经出现”);
}
移除子视图时先发生
视图将要消失
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@”视图将要消失”);
}
移除子视图时后发生
视图已经消失
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
NSLog(@”视图已经消失”);
}