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


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

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

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

    [objc] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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] view plaincopy在CODE上查看代码片派生到我的代码片
     
    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:方法创建的时候,根本就不会被调用

  • 相关阅读:
    千年决心
    编译器及其命令行模式杂谈
    How Microsoft Lost the API War
    再看计算机本科该如何学习
    C++杂记(一)
    C++杂记
    Java IO 学习心得
    VMDq (Virtual Machine Device Queue) in OpenSolaris
    WCHAR and wchar_t 的区别 (zz)
    error C3225: generic type argument for 'T' cannot be 'System::Collections::Generic::KeyValuePair ^',
  • 原文地址:https://www.cnblogs.com/wangjuneng/p/4554522.html
Copyright © 2020-2023  润新知