视图控制器

Posted llstart-new0201

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了视图控制器相关的知识,希望对你有一定的参考价值。

视图控制器UIViewController,视图控制,在新版本xcode中会默认生成一个ViewController。

(一)新建UIViewController

右键->New File添加一个继承自UIViewController的类View1Controller,在viewDidLoad中添加button,并设置button点击事件为关闭此ViewController

    self.view.backgroundColor=[UIColor redColor];
    
    UIButton *closeViewBtn=[[UIButton alloc] init];
    closeViewBtn.backgroundColor=[UIColor blueColor];
    closeViewBtn.frame=CGRectMake(10, 30, 100, 30);
    [closeViewBtn setTitle:@"Close" forState:UIControlStateNormal];
    [closeViewBtn addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:closeViewBtn];

点击事件

-(void) closeView
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

(二)在ViewController中添加一个button用来控制View1Controller的启动出现

    //ViewController
    UIButton *showView1Btn=[[UIButton alloc] init];
    showView1Btn.frame=CGRectMake(10, 470, 100, 30);
    showView1Btn.backgroundColor=[UIColor redColor];
    [showView1Btn addTarget:self action:@selector(showView1:) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:showView1Btn];
-(void) showView1:(UIButton *)showView1Btn
{
    View1Controller *view1=[[View1Controller alloc] init];
    [self presentViewController:view1 animated:YES completion:^{}];
}

通过上述两步可以实现视图的简单切换。

(三)视图的生命周期

在view1Controller中添加如下代码,在其启动过程中可以看到除viewDidLoad外其他方法的触发以及启动顺序

-(void) loadView
{
    [super loadView];
    NSLog(@"Load view");
}

-(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];
    NSLog(@"View will disappear");
}

-(void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"View did disappear");
}

-(void) closeView
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

 

以上是关于视图控制器的主要内容,如果未能解决你的问题,请参考以下文章

如果使用导航控制器,如何删除某些片段中的底部导航视图和工具栏?

如何使控制台中的视图缓存片段过期?

如何将这个 Objective-C 代码片段写入 Swift?

在扩充XML文件之后,不会调用onCreate()

动画未按照编写代码的顺序运行

底部导航视图中的每个选项卡单击都会重新加载片段