UIViewController 是一个管理数据(model)和视图(view)的控制器, 是MVC设计模式中最重要的部分
UIViewController的使用
UIViewContorller是一个抽象基类,我们在使用它的时候一般都去创建一个它的子类
1.给window设置一个根视图控制器
//1. 创建一个viewController
MainViewController *mainVC = [[MainViewController alloc]init];
//2. 将window的rootViewController属性设置为mainVC对象
self.window.rootViewController = mainVC;
[mainVC release];
2. 指派初始化方法
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
NSLog(@"%s", __FUNCTION__);
if (self) {
// Custom initialization
//数据的处理 在初始化方法中写
}
return self;
}
// 视图结束加载
//viewController自带的view加载完毕的时候调用
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//一般的视图操作(添加视图, 改变视图设置)都在这个方法中
self.view.backgroundColor = [UIColor purpleColor];
UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
button.frame = CGRectMake(20, 120, 280, 40);
[button setTitle:@"点击" forState:(UIControlStateNormal)];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
NSLog(@"%s", __FUNCTION__);
}
// button 的响应方法
- (void)buttonClicked : (UIButton *)button
{
// 弹出新的试图控制器
// 1.创建第二个试图控制器
SecondViewController *secondVC = [[SecondViewController alloc]init];
// 2.弹出
// 参数1: 需要弹出的viewController
// 参数2: 是否需要动画效果
// 参数3: 弹出执行完毕之后 执行块(Block)里的代码
[self presentViewController:secondVC animated:YES completion:^{
// code
}];
}
//viewController的生命周期 方法
//视图(view)已经出现
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"%s", __FUNCTION__);
}
// 视图已经消失
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
NSLog(@"%s",__FUNCTION__);
}
// 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"%s", __FUNCTION__);
}
//视图将要消失
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"%s",__FUNCTION__);
}
// 收到内存警告时 会调用这个方法
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
NSLog(@"%s", __FUNCTION__);
}