6

我有一个 UIViewController 在主视图上处理几个 UIImageViews。底部是一个 UIToolbar,其中包含一些要与之交互的项目。

现在,当我旋转设备时,我不希望 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?

谢谢你的帮助!

4

1 回答 1

7

尝试使用 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;
    }
}
于 2013-11-13T11:19:09.900 回答