2011-07-08 66 views
1

當用戶點擊UIView(全屏)時,我的應用需要檢測方向並執行一些操作。但是有一個小問題。 如果我以橫向模式啓動應用程序,並且用戶點擊背景'interfaceOrientation'變量爲'0',並且我不知道如何重新排列視圖元素。如果我旋轉模擬器一旦一切都很好,但如果不'interfaceOrientation'是'0'。在這裏做什麼?iPad界面方向問題

UIInterfaceOrientation interfaceOrientation = [[UIDevice currentDevice] orientation]; 

if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) 
    {   
     ...    
    } 
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) 
    {  
     ... 
    } 
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight) 
    { 
... 
} 
+0

你是從視圖控制器的viewDidLoad調用'[super viewDidLoad]'嗎? – highlycaffeinated

+0

是的,我叫它,但它仍然是'0' – 1110

+0

如果你在你的'viewDidLoad'中向'[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]添加了一個調用,會發生什麼? – highlycaffeinated

回答

3

我不確定可以解決的問題。 UIDeviceOrientationUnknown爲0.這意味着,特別是對於沒有陀螺儀的iPad,此時的方向根本不知道。想象一下你的iPad放在一張桌子上,並且用戶正在啓動應用程序:除非您相應地傾斜設備,否則沒有任何方法可以定義應用程序實際上是以橫向或縱向方式運行的。因此..啓動時的方向始​​終爲0(未知)。

+0

接縫這是真正的問題。如果應用程序已啓動且設備未旋轉,則方向未知。 Grrr ...任何人都有這個解決方案? – 1110

+0

因此,如果應用程序在桌面上啓動,它將不會有方向設置,所以我接下來做了。如果方向未知,我設置視圖元素位置,如果用戶不喜歡他必須旋轉設備。愚蠢的解決方案,但我沒有看到另一種方式。 – 1110

0

如果您無法從您的視圖控制器訪問self.interfaceOrientation,您應該能夠訪問[UIApplication sharedApplication].statusBarOrientation

另外,有時在viewDidLoad中有時調用self.interfaceOrientation會有風險,因爲視圖會在知道其方向之前加載,所以它會在之後執行旋轉。在這種情況下,請嘗試在viewWillAppear中找到它。

或者只是覆蓋willRotateToInterfaceOrientation:duration並將該信息傳遞給需要它的UIView。注意:如果您將xib設置爲該方向,則不會調用該方法。

2

您正在將UIDeviceOrientation類型投射到UIInterfaceOrientation類型。設備的方向有幾個不同於接口方向的值。

嘗試使用:

UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation]; 

switch (deviceOrientation) { 
    default: 
    case UIDeviceOrientationPortrait: 
    case UIInterfaceOrientationPortraitUpsideDown: 
    case UIDeviceOrientationUnknown: 
     //... 
     break; 
    case UIDeviceOrientationLandscapeLeft: 
     //... 
     break; 
    case UIDeviceOrientationLandscapeRight: 
     //... 
     break; 
} 

編輯:如果設備的方向是未知的,你應該剛剛成立的正規縱向視圖。

+0

當我這樣做時,我得到:UIDeviceOrientationUnknown – 1110