2014年1月16日 星期四

iOS 鎖定頁面翻轉(Lock The Orientation of ViewController)


鎖定頁面翻轉(Lock The Orientation of ViewController)

首先,我們先來簡單介紹一下什麼是頁面翻轉,頁面翻轉主要是透過手機內部的感應器進行偵測,也因此當我們在開發手機應用時,就必須留意是否要開放頁面翻轉的功能供使用者使用。

在Xcode中,我們可以透過專案的設定進行頁面翻轉的設定,如下圖所示:
在圖片的中間部份我們可以看到"Device Orientation"有四個選項,可分別對應到下圖的示意圖中。
但,這邊筆者需特別提醒各位看倌,這是"專案設定",因此,設定將會影響到所有的頁面!

在這次專案開發的過程中,筆者就遇到了一個問題,如果我的第一個頁面不想讓頁面旋轉,但是第二個頁面卻又需要使用旋轉的功能呢?偏偏在ViewController又不能獨立設定頁面的翻轉,於是…經由神通廣大的Google大神身上找到了解法。

而接下來,也是本文的重點啦,如何獨立設定各個頁面可翻轉的功能呢?

首先,在專案設定中,先將專案設定為允許所有的頁面都可翻轉,可參照剛剛頁面翻轉的設定圖,進行設定。

接著,在ViewController中的@implementation後面加上這個function
- (NSUInteger)supportedInterfaceOrientations
{
    return 頁面翻轉屬性設定;
}
然後由下列的參數中選擇需要的參數填入return值的<頁面翻轉屬性設定>中就可以只針對該畫面進行頁面翻轉設定的功能囉。
  1. UIInterfaceOrientationMaskAll:允許全部的頁面翻轉功能。
  2. UIInterfaceOrientationMaskAllButUpsideDown:允許全部的翻轉除了UpsideDown以外。
  3. UIInterfaceOrientationMaskLandscape:僅允許頁面左右翻轉。
  4. UIInterfaceOrientationMaskLandscapeLeft:僅允許Landscape left翻轉。
  5. UIInterfaceOrientationMaskLandscapeRight:僅允許Landscape Right翻轉。
  6. UIInterfaceOrientationMaskPortrait:僅允許Portrait。
  7. UIInterfaceOrientationMaskPortraitUpsideDown:僅允許UpsideDown
單一屬性範例:允許所有的頁面翻轉功能。
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
多重屬性範例:只允許Portrait及UpsideDown的這兩種模式,如果還需要增加其他屬性用加號連接即可。
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait+
    UIInterfaceOrientationMaskPortraitUpsideDown;
}

沒有留言:

張貼留言