用代码创建并实例化在storyboard中声明的ViewController


http://kyfxbl.iteye.com/blog/1997502

我们的项目最早是基于storyboard开发的,所以一开始所有的ViewController都通过storyboard创建,并通过segue连接跳转

但是今天其中一个controller的view,我们需要特别美化一下,用storyboard做很麻烦。所以就把它从storyboard里拿出来了。问题是,原来的segue就不能用了,需要用编码的方式来实现涉及到此controller的跳转

跳转进此controller的代码很常规,之前做模态页面开发的时候已经试过了,所以很简单就写出来:

Objc代码   收藏代码
  1. YLSBootstrapViewController *bootstrapViewController = [[YLSBootstrapViewController alloc] initWithNibName:nil bundle:[NSBundle mainBundle]];  
  2. bootstrapViewController.view = [[YLSBootstrapView alloc] initWithFrame:CGRectNull];  
  3. [self presentViewController:bootstrapViewController animated:YES completion:nil];  

上面3行代码,分别创建controller,view,以及跳转。但是要从这个controller跳到下一个controller不知道怎么写,因为下一个controller还是由storyboard负责加载和实例化的,不能通过调用initWithNibName:bundle:来创建

搜索了一下,网上说storyboard创建controller,内部调用的是initWithCoder方法,所以在这个方法上研究了一会,最后也没成功,主要是不知道应该如何传参。最后发现方向错了,应该调另一个API:

Objc代码   收藏代码
  1. // 从storyboard创建MainViewController  
  2. UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"nailshop" bundle:[NSBundle mainBundle]];  
  3. YLSMainViewController *mainViewController = (YLSMainViewController*)[storyboard instantiateViewControllerWithIdentifier:@"mainViewController"];  
  4. [self presentViewController:mainViewController animated:YES completion:nil];  

在调用之前,需要在storyboard里,给目标ViewController设置identifier


这样就可以通过编码方式,创建storyboard中的ViewController了

PS:

创建ViewController的方式主要就2种。如果通过代码的方式,就调用initWithNibName:bundle:方法;如果是通过storyboard自动创建,则storyboard会隐式调用initWithCoder:方法,这个API一般不需要开发者直接调用,而是通过storyboard API来间接调用。而UIViewController自身的各生命周期方法,根据创建方式的不同,在调用上也会有区别,比如说viewDidLoad方法,在通过initWithNibName:bundle:方法创建的时候,根本就不会被调用


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值