ios6 – 检测UIViewController上的接口旋转,即使未在 – (NSUInteger)supportedInterfaceOrientations中定义

我有一个UIViewController在主视图上处理几个UI ImageViews.在底部一个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?

谢谢你的帮助!

解决方法

尝试使用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;
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...