iOS中ViewController的四种创建方法

1189人浏览 / 0人评论 / 添加收藏

要实现的功能:从一个VC中点击Button跳转到另一个VC

首先将第一个视图里button的点击方法拖到ViewController.m文件中

- (IBAction)ClickBtn:(id)sender {}

一.StoryBoard里面获取ViewController

1.在StoryBoard里创建一个VC,并设置它的StoryBoard ID

2.创建VC的文件,继承自UIViewController,为了命名方便,我这里直接命名为ViewController1

3.在ViewController.m

- (IBAction)ClickBtn:(id)sender {    //获取当前的Storyboard    UIStoryboard*sb=[UIStoryboard storyboardWithName:@"Main" bundle:nil];    //在Storyboard中获取vc1    ViewController1*vc1=[sb instantiateViewControllerWithIdentifier:@"vc1"];    //呈现出vc1    [self presentViewController:vc1 animated:YES completion:^{    }];}

二.Xib文件初始化

1.创建VC的文件,继承自UIViewController,为了命名方便,我这里直接命名为ViewController2

2.在Xib中

3.在ViewController.m

- (IBAction)ClickBtn:(id)sender {    //initWithNibName后+vc2文件名    ViewController2*vc2=[[ViewController2 alloc]initWithNibName:@"ViewController2" bundle:nil];    //呈现出vc2    [self presentViewController:vc2 animated:YES completion:^{    }];}

三.纯代码创建

1.创建VC的文件,继承自UIViewController,为了命名方便,我这里直接命名为ViewController3

2.代码设置背景色,创建button

    self.view.backgroundColor=[UIColor whiteColor];    UIButton*btn=[UIButton buttonWithType:UIButtonTypeCustom];    btn.frame=CGRectMake(100, 100, 100, 100);    [btn setTitle:@"出去" forState: UIControlStateNormal];    [btn addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];    btn.backgroundColor=[UIColor blueColor];    [self.view addSubview:btn];

3.在ViewController.m

- (IBAction)ClickBtn:(id)sender {    ViewController3*vc3=[[ViewController3 alloc]init];    //呈现出vc3    [self presentViewController:vc3 animated:YES completion:^{    }];}

四.可视化操作

五.从第二个视图回到第一个视图操作很简单,仅在第二个VC的button点击事件中加上这样一句代码

[self dismissViewControllerAnimated:YES completion:^{        NSLog(@"vc跳出");    }];

 

全部评论