2013-01-17 43 views
6

中定義檢測UIViewController上的接口旋轉我有一個UIViewController處理主視圖上的幾個UIImageViews。在底部是一個UIToolbar,有幾個項目可以互動。即使沒有在 - (NSUInteger)supportedInterfaceOrientations

現在,當我旋轉設備,我不希望viewController旋轉,但只是UIImageViews。換句話說,底部的工具欄位於左側(或右側),但imageViews會正確旋轉。

所以,通過使用這些方法

- (BOOL)shouldAutoRotate { 
    return YES; 
} 

- (NSUInteger)supportedInterfaceOrientations { 
    return UIInterfaceOrientationMaskPortrait; 
} 

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 
// rotate the image views here 
} 

在設備上的任何轉動將不會被執行相結合,因爲只有一個接口取向是支持(UIInterfaceOrientationMaskPortrait)。但是當我添加另一個界面方向以支持supportedInterfaceOrientations-方法時,視圖控制器也將旋轉。

即使只支持一個方向,我如何檢測視圖控制器的旋轉?或者還有另一種可能性,可以根據不斷變化的設備方向旋轉UIViews?

感謝您的幫助!

+0

找到了答案 - 當然 - 10秒後在這裏:ht TP://stackoverflow.com/questions/14387735/can-i-observe-when-a-uiviewcontroller-changes-interfaceorientation – uruk

回答

8

嘗試使用UIDevice實例來檢測設備物理方向的更改。 要開始接收通知,您可以使用這樣的事情(在viewWillAppear:方法爲例):

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

    //No reason to ask NSNotification because it many cases `userInfo` equals to 
    //@{UIDeviceOrientationRotateAnimatedUserInfoKey = 1;} 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDidRotate) name:@UIDeviceOrientationDidChangeNotification object:nil]; 
} 

對於取消註冊接收設備旋轉活動,用這個(在viewWillDisappear:爲例):

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; 
} 

而且這是一個例子deviceDidRotate功能:

- (void)deviceDidRotate { 
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

    switch (orientation) { 
     case UIDeviceOrientationPortrait: 
     case UIDeviceOrientationPortraitUpsideDown: 
      // do something for portrait orientation 
      break; 
     case UIDeviceOrientationLandscapeLeft: 
     case UIDeviceOrientationLandscapeRight: 
      // do something for landscape orientation 
      break; 

     default: 
      break; 
    } 
}