2012-01-05 90 views
7

我加入一個UIViewUIWindow這不是keyWindow。當設備旋轉時,我想讓UIView旋轉。 窗口上的任何特殊屬性或我需要設置的視圖?目前視圖不旋轉。的UIView子視圖不旋轉

我所知道的一個事實,即只有應用程序的keyWindow的第一子視圖講述設備旋轉。作爲一項測試,我將我的觀點添加到keyWindow的第一個子視圖中。這會導致視圖旋轉。然而,作爲keyWindow的第一個子視圖的子視圖的視圖不適用於各種美學原因。

的另一種方法是觀察在視圖設備取向的變化和寫入旋轉代碼自己。不過,如果可能的話,我想避免編寫這些代碼(在我看來,額外的窗口更清晰)。

回答

7

的UIView不處理旋轉,確實的UIViewController。 因此,所有你需要的是創造一個UIViewController,它實現shouldAutorotateToInterfaceOrientation,並將此控制器作爲RootViewController的到你的UIWindow

類似的東西:

UIViewController * vc = [[[MyViewController alloc] init] autorelease]; 

    vc.view.frame = [[UIScreen mainScreen] bounds]; 
    vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4]; 

    //you vc.view initialization here 

    UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    window.windowLevel = UIWindowLevelStatusBar; 
    window.backgroundColor = [UIColor clearColor]; 
    [window setRootViewController:vc]; 
    [window makeKeyAndVisible]; 

,我用這個MyViewController,因爲我希望它反映的主要應用

@interface MyViewController : UIViewController 

    @end 

    @implementation MyViewController 

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
    { 
     UIWindow *window = ((UIWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0]); 
     UIViewController *controller = window.rootViewController; 

     if (!controller) { 
      NSLog(@"%@", @"I would like to get rootViewController of main window"); 
      return YES; 
     } 
     return [controller shouldAutorotateToInterfaceOrientation:toInterfaceOrientation]; 
    } 
    @end 

的變化,但你總是可以只返回YES任何方向或寫你的邏輯,如果你想。

+0

我有一個類似的問題 - 一個UIWindow和它的觀點似乎並沒有被旋轉的 - 這解決似乎不工作爲了我。我讓窗口的rootViewController成爲一個成功旋轉子視圖的控制器,但窗口的子視圖根本不旋轉。 – 2013-06-24 20:58:29

+0

他們不應該,因爲他們沒有附加到UIViewController和只有UIViewController管理旋轉 – 2013-06-29 21:08:21

+0

這是一個很好的答案,謝謝。它在一個二級窗口「Just Work」上進行輪換。稍後要從屏幕上刪除窗口,只需將其rootViewController設置爲nil,並將其引用給自己,以便ARC可以將其解除分配。 – nobre 2013-10-18 12:44:42

2

您可以在下面的代碼添加到您的項目

[NSNotificationCenter defaultCenter]的addObserver:自我選擇:@選擇(didRotate :) 名稱:UIDeviceOrientationDidChangeNotification對象:無]。

,並創建以處理它的函數。

+0

我寧願讓旋轉的「自由」,而不是寫'didRotate' – SundayMonday 2012-01-05 04:31:50