Using PushPop demo to learn basic Navigation Controller

在 iTunes U 上面有一系列非常有名的 iPhone application development program在 Stanford 開的課程錄影。而在該堂客講師 Josh Shaffer 講到 Navigation 時候,我邊看著影片也邊跟著動手做了簡單的 Demo來學 Navigation Controller 的功能。這個範例透過 Navigation Controller,讓第一頁開啓後,畫面上顯示一個按鈕,按下按鈕,會轉換到第二頁,再從上方可以點選 Previous 按鈕回到第一頁,達到彼此 Navigate 效果,非常簡單的體驗,後來我也額外加入了第三頁,讓它可以做到三層 Navigate 效果。

Navigation Controller 採用 Stack-based design 概念,用了『先進後出 First in last out』的做法,而透過 Stack 相關辭彙 push, pop 來做出放進取出,所以當程式用到 push 時候,是往下更深入走一層,用到 pop 時候,是往回走到上層。每一個 Navigation Controller 擁有一個 root view controller,當走到 Root 時候,就是為最上層了。

使用 Windows base application 做起頭,將 Project 命名為 PushPop。在 Classes 區新增兩組 ViewController 以及包含 .xib 檔案,命名為 FirstViewController 和 SecondViewController, ThirdViewController。

在 FirstViewController 定義一個 IBAction pushViewController 的 method,在 xib 檔案透過 Interface Builder 拖拉出一個 Button 並且把它 event 效果和這個 method 串連起來。這樣我們可以回到 Implement 檔案將該 Method 實作。

在 SecondViewController, ThirdViewController ,只要打開 xib 檔案在 Interface Builder 裡面拖拉出一個 UILabel,顯示訊息,這樣即可。

一開始會有 PushPopAppDelegate.h,裡面宣告 UINavigationController,打算從 Xcode 裡面裝置 Navigation Controller。

接著在 Implement 檔案 PushPopAppDelegate.m 裡面開設實作


因為我們預計在這邊來規劃我們的 Navigation Controller。這個 method 會在 application launch 結束後,最先進來的地方。並且將 FirstViewController 宣告初始化,可以設定它的 title 為 "First",接著讓 Navigator Controller 一開始就 push view 為 FirstViewController,在把這個 Navigator Controller 加到 window 的 subview。如果這時候 Build & Run 已經可以看到一開始畫面是 FirstViewController 了。


再來進入到 FirstViewController.m 實作 pushViewController method,在這邊將 SecondViewController 宣告初始化後,將它標題設為 "Second",接著再把 Navigation Controller pushView 設定為 SecondViewController,將 Animated 效果設定為 Yes。


而要將 SecondViewController 導到 ThirdViewController 在實作 method 地方加入 pushViewController 導到 thirdViewController。


當完成以上後 Build & Run,即可從模擬器裡面簡單做出三個頁面和彼此互相 Navigation 的效果。以上如果有興趣可以到 github 上面進一步瞭解 Code edwardinubuntu / PushPop

Comments