建立控制器的幾種方式,建立控制器幾種

來源:互聯網
上載者:User

建立控制器的幾種方式,建立控制器幾種

建立控制器的方式:

  <方式1>直接建立:

        XZOneViewController *one = [[XZOneViewController alloc] init];
          one.view.backgroundColor = [UIColor redColor];
          self.window.rootViewController = one;

 

  <方式2>通過storyboard建立:

    1. 主動載入storyboard (從現成的storyboard裡面載入已經描述好了的東西)

    // 1.0 先建立一個storyboard檔案 Two.storyboard,但是在Main Interface中不設定成啟動載入main storyboard(去掉main)。

 

        // 1.1 載入storyboard檔案,並沒有建立storyboard裡面的控制器。

    // 傳nil代表mainBundle,操作storyboard對象意味著操作Two.storyboard檔案。
           UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Two" bundle:nil];

 

    // 1.2 建立storyboard裡面的控制器

    // 1.2 情況一:

        // UIViewController *vc = [storyboard instantiateInitialViewController]; // 返回的是箭頭所指的控制器

    // 1.2 情況二:
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"pink"]; // 此控制器是沒有箭頭指向的控制器,identifier是pink

      self.window.rootViewController = vc;

    // 1:

           

 

    2. 設定為storyboard為整個程式最主要storyboard,程式已啟動就會去載入Main.storyboard:

    自動產生載入storyboard代碼為:

            // 1.建立window
            self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
            // 2.載入storyboard,並且建立初始化控制器(箭頭所指的控制器)
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            self.window.rootViewController = [storyboard instantiateInitialViewController];
   
            // 3.顯示視窗
            [self.window makeKeyAndVisible];

 

    載入主要storyboard會完成三件事情:

    1> 建立視窗

    2> 建立箭頭所指的 Initial View Controller。

    3> 並設定控制器為視窗的根控制器。控制器的view就顯示在window上面了。

 

    總結:1. 沒有主動去載入storyboard,storyboard不會憑空冒出來;

       2. 只要設定了主視窗,會自動產生載入storyboard代碼。
            

  <方式3>指定xib檔案來建立:

      XZViewController *viewVc = [[XZViewController alloc] initWithNibName:@"xzVc" bundle:nil]; // 這之前已經建立了一個xzVc.xib檔案,記得把xib的view拖給相應的控制器(file‘owner)。

 

 

=======附=======注=為MJ視頻中==================

    

 

     

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.