UIViewController视图控制器视图的生命周期

//vc初始化的时候,view并没有被创建出来
 RootViewController *root = [[RootViewController alloc] init];
 //第一次使用root的view属性时,view被自动创建出来
 self.window.rootViewController = root;

//这一系列方法,称为视图控制器视图的生命周期
//一般情况下,loadView 和viewDidLoad只调用一次
//视图要创建,会先触发 loadView方法
- (void)loadView{
    [super loadView];//重写此方法,必须写[super loadView],让UIViewController创建一个view的对象
    NSLog(@"loadView!");
}

//将view加载到内存中(给到vc),此时,视图还不可见
- (void)viewDidLoad
{
    [super viewDidLoad];//会完成一些必要的初始化操作
    //一般将代码写在[super viewDidLoad]之后
    //可以写变量的初始化和视图的添加操作
    NSLog(@"view Did load!");
    self.view.backgroundColor = [UIColor yellowColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(10,30,300,50);
    [btn setTitle:@"sub" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    // Do any additional setup after loading the view.
}
- (void)btnClicked{
    SubViewController *sub = [[SubViewController alloc] init];
    //通过模态化的方式,呈现sub的view:实际上的操作是将root的view从window上移除,将sub的view添加到window上
    //设置视图的切换方式
    sub.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:sub animated:YES completion:^{
        
    }];
}

/********可以被调用多次********/
//视图即将出现时,触发此方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"view will Appear!");
}
//视图已经出现,触发此方法
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"view did appear!");
}
//即将消失
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //__FUNCTION__ 打印函数的名称
    NSLog(@"%s",__FUNCTION__);
}
//已经消失
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSLog(@"%s",__FUNCTION__);
}

//当内存告急的时候,会触发此方法
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//在dealloc方法中 view会随着vc的销毁而自动被销毁
- (void)dealloc{

}

 

posted @ 2015-04-07 20:32  孤独的根号下三  阅读(179)  评论(0编辑  收藏  举报