Autorotation and Autosizing

iPhone 允許應用程式當 Runtime 時候,使用者翻轉裝置時候,畫面也要跟著變動,支援 Portrait (高瘦型) 畫面和 landscape (矮寬型) 畫面兩種模式。想要體驗這種效果,可以打開 iPhone's web browser Safari 來體驗。我們的程式也可以支援這樣形式。

在 Interface Builder 裡面拖拉元件 (例如 UIButton) 進來,按下該元件打開 Inspector,切換到 view size ,在 Autosizing 區可以透過裡面的紅色箭頭,按下或者取消按下各種方向,來決定這個元件當翻轉時候要怎麼運作。在框框的外圍四周按下可以決定當翻轉的時候,要定位的位置。框框的內圍按下可以決定當翻轉時候,是否因為畫面大小而做自動化調整。這邊可以透過設定方式,讓畫面元件做出自動化調整。

當然元件透過 Interface Builder 拉出來的,要跟 Xcode 的程式碼連在一起,不要忘記透過定義 IBOutlet 將彼此串聯起來,如果要做出 event 處理,加入 IBAction 串聯起來再到該 method 實作程式碼出來。在 Xcode 裡面,我們也能透過程式來控制翻轉特效,首先要了解有四個指標用來判定目前裝置的狀態:UIInterfaceOrientationPortrait (畫面正向), UIInterfaceOrientationPortraitUpsideDown (畫面上下顛倒), UIInterfaceOrientationLandscapeLeft (畫面躺平 Home 鍵朝左), UIInterfaceOrientationLandscapeRight (畫面躺平 Home 鍵朝右)。

使用 view-based application template 裡面,在 ViewController.m 可以透過兩個 methods 來控制當 iPhone 裝置翻轉時候,是否支援翻轉,另外當翻轉時候畫面要做什麼事情。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {...}
這個 method 是當 iPhone 翻轉的時候,決定要不要讓畫面和畫面裡面的元件支援翻轉。裡面可以透過 interfaceOrientation 來判定目前是哪一種導向指標,可以來做判斷,最後回傳是否支援翻轉效果,例如回傳 return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);。如果通通翻轉,這邊回傳 YES 即可。


- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{...}
這個 method 裡面可以配製當畫面翻轉到哪一種狀態,讓畫面裡面的元件可以做出什麼樣的特效,例如讓按鈕的框框可以對到哪個座標以及它的大小。 button1.frame = CGRectMake(20, 20, 125, 125); CGRectMake 是給與四個參數(座標 x, y 和長和寬),它會回傳CGRect 四方形回來。

以上可以參考書本 Beginning iPhone 3 Development 章節 Autorotation and Autosizing,或者下載 github 練習範例 https://github.com/edwardinubuntu/AutoSize

Comments