回答

14

使用UIApplication的statusBarOrientation屬性。如果使用設備方向,如果它是UIDeviceOrientationFaceUpUIDeviceOrientationFaceDown,則可能會遇到問題。

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; 
if (UIInterfaceOrientationIsLandscape(orientation)) 
{ 
    // Do something when in landscape 
} 
else 
{ 
    // Do something when in portrait 
} 
+0

在ios 9中已棄用 – trickster77777

2

當應用程序加載時,它不知道它的當前定位 -

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation]; 
if (orientation == UIDeviceOrientationPortrait) { 
    NSLog(@"portrait");// only works after a rotation, not on loading app 
} 

一旦你旋轉設備,你會得到正確的方向,但在加載應用程序時,不要改變方向,似乎使用[[UIDevice currentDevice] orientation]不知道當前的方向。

所以,你需要做兩件事情 -

  1. 嘗試在plist文件設置應用程序的接受裝置定向
  2. 在你UIViewControllers,你將需要重寫shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)方法時,應用程序返回YES應該rotate:
+0

我想你是誤會我的問題 - 我的方向改變罰款(我已經定義shouldAutorotate的話),但我想知道哪些變量,我可以檢查,看看我是什麼方向目前在。 – Gibson

+0

檢查我更新的答案。你需要實現 - 'UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];' –

+1

@Srikar我用'[[UIDevice currentDevice]方向]'爲此目的一次,並最終有一個錯誤在我的代碼時, UIDeviceOrientationFaceUp'或'UIDeviceOrientationFaceDown'。這是當我切換到使用'[UIApplication sharedApplication] .statusBarOrientation',這是'UIInterfaceOrientation'類型而不是'UIDeviceOrientation'。請注意,您不必顯示該代碼的狀態欄即可運行。我想在進行修改之前,我甚至在遇到面朝上/面朝下的錯誤時使用宏UIDeviceOrientationIsLandscape(deviceOrientation)。 – Sam

1

如果是相關的調用順序意味着你不能依靠interfaceOrientation具有viewWillAppear正確的值,那麼 - 假設括號t視圖控制器旋轉 - 最安全的事情可能是self.parentViewController.interfaceOrientation。如果沒有,你可以嘗試從[[UIDevice currentDevice] orientation]做出第一個假設,這可能並不總是100%(例如,當你的應用程序啓動時該設備平躺在桌子上),但可能會給你一個比總是更好的猜測假設肖像。

4
UIDeviceOrientation getCurrentOrientation() { 
    UIDevice *device = [UIDevice currentDevice]; 
    [device beginGeneratingDeviceOrientationNotifications]; 
    UIDeviceOrientation currentOrientation = device.orientation; 
    [device endGeneratingDeviceOrientationNotifications]; 

    return currentOrientation; 
} 

這是給你轉換的UIDeviceOrientationUIInterfaceOrientation

+0

這是唯一一個適合我的解決方案!謝謝! – maza23

相關問題