2012-04-26 52 views
5

我需要從ViewController獲取設備方向。 我不能立足於如何通過UIView參考獲取設備方向?

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

,因爲它(當裝置規定在桌子上例如)有時會返回取向是未知的。

我只需要知道什麼方向是我目前的UIView顯示(它是風景左側還是右側風景)。我不需要在改變方向時更新這個值,我只是想知道它,當我要求時。只是一些參考view.orientation;)。有什麼能幫助我嗎?我讀過UIView文檔,發現了一些對UIWindow的引用,但沒有任何東西可以幫助我。

回答

13

您也可以從UIApplication的設備的方向,你有沒有嘗試過使用

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; 
+1

這正是我所喜歡的爲...而努力。現在我可以獲取UIKit組件的方向並使用它。非常感謝! – thelion 2012-04-27 07:10:07

-1

以下是示例代碼來這樣做。有一個名爲deviceOrientation的變量,無論何時被詢問,它都會回答設備的當前方向。

UIDeviceOrientation deviceOrientation; 

- (void)viewWillAppear:(BOOL)animated 
{ 
    deviceOrientation = (UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation]; 
    [self willAnimateRotationToInterfaceOrientation:deviceOrientation duration:0.5]; 
} 

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration 
{ 
    deviceOrientation = (UIDeviceOrientation)interfaceOrientation; 
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
    { 
     NSLog(@"Landscape"); 
    } 
    else 
    { 
     NSLog(@"Portrait"); 
    } 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return TRUE; 
} 
4

的UIViewController有一個屬性

UIInterfaceOrientation interfaceOrientation; 

所以在UIViewController,你可以在任何時間通過

UIInterfaceOrientation myCurrentOrientation = self.interfaceOrientation; 
+0

自iOS 8.0以後不推薦使用 – 2017-07-23 14:33:59

0

斯威夫特版本

let currentOrientation:UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation 


    if currentOrientation.isPortrait { 

     print("PORTRAIT") 

    } else if currentOrientation.isLandscape { 

     print("LANDSCAPE") 

    } 
訪問設備的當前方位