行動裝置螢幕有限,所有內容都得放在單一視窗組成的單一介面中顯示,在 iOS 中體現為視圖切換。當一個視圖替換掉另一個視圖時,常會使用動畫效果,這項任務便交由視圖管理器(視圖控制器)完成。
iOS 5 之後,應用程式視窗有一個根視圖控制器(rootViewController)。若不為 rootViewController 賦值,會出現「Application windows are expected to have a root view controller at the end of application launch」的警告。
第一種:程式碼(結構清晰易懂,個人偏好):
[[ViewController alloc] init]; [[ViewController alloc] initWithNibName:@"xibName" bundle:nil];
第二種:代理類加載 xib:在 xib 中放入一個 ViewController,並將 File's Owner 的 class 設為應用程式代理類;於代理類加入 ViewController 插座變數並連線;最後在 application:didFinishLaunchingWithOptions: 中載入 xib。
第三種:串聯圖(Storyboard)。
UIViewController 中有 loadView 方法。預設情況下視圖控制器並未重寫此方法;經測試,第一次存取 view 屬性時便會自動呼叫 loadView。重寫方式如下:
- (void)loadView {
self.view = [[UIView alloc] init];
}
其效果與不重寫相同,可推測未使用 xib 時 UIViewController 的 loadView 也是類似實作。
UIViewController 中宣告了以下方法,可重寫以進行生命週期管理:
- (void)loadView; // 載入視圖 - (void)viewDidLoad; // 已經載入 - (void)viewWillAppear:(BOOL)animated; // 視圖將要顯示 - (void)viewDidAppear:(BOOL)animated; // 視圖已經顯示 - (void)viewWillDisappear:(BOOL)animated;// 視圖將要隱藏 - (void)viewDidDisappear:(BOOL)animated; // 視圖已經隱藏 - (void)viewWillLayoutSubviews; // 將要呼叫 layoutSubviews - (void)viewDidLayoutSubviews; // 已經呼叫 layoutSubviews
視圖控制器的一項主要任務,就是知道如何旋轉視圖。旋轉可分為兩種:
· 抵消旋轉:應用的旋轉是為了抵消裝置方向的旋轉,讓 App 依使用者握持方式正確顯示。挑戰在於螢幕並非正方形,旋轉 90 度後介面不再適合螢幕,必須做出調整來抵消。
· 強制旋轉:當特定視圖出現時進行旋轉,或在啟動時提示使用者旋轉裝置才能正確顯示。由於介面往往只針對特定方向(直向或橫向)設計,螢幕又非正方形,因此實際上只能顯示某一特定模式。
為支援旋轉,視圖控制器需重寫 shouldAutorotateToInterfaceOrientation:,傳入參數為當前裝置方向:
UIInterfaceOrientationPortrait // Home 鍵在下方 UIInterfaceOrientationPortraitUpsideDown // Home 鍵在上方 UIInterfaceOrientationLandscapeLeft // Home 鍵在左邊 UIInterfaceOrientationLandscapeRight // Home 鍵在右邊
回傳 YES 允許該方向旋轉,否則回傳 NO。若未重寫,預設僅 Portrait 回傳 YES。
iOS 5 新增了 shouldAutorotateToInterfaceOrientation 的動態實作,可使用 attemptRotationToDeviceOrientation 方法。其使用情境為:interface orientation 與 device orientation 不一致,但希望透過重新指定 interface orientation 的值,立即實現兩者一致。關鍵在於能否「立即」實現——若只更改了支援的 interface orientation 值而未呼叫 attemptRotationToDeviceOrientation,則要等下次裝置方向變化時才會一致。
舉例:若當前 interface orientation 只支援 Portrait,當 device orientation 變成 Landscape 時,畫面仍顯示 Portrait;若此時希望立即同步為 Landscape,需先將 supportedInterfaceOrientations 的返回值改為 Landscape,再呼叫 attemptRotationToDeviceOrientation,系統便會重新詢問並立即更新。
旋轉事件:可透過 interfaceOrientation 屬性得知當前介面方向,UIViewController 子類可重寫以下方法以在旋轉前後收到通知:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)to duration:(NSTimeInterval)duration - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)to duration:(NSTimeInterval)duration - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)from