如何旋转控制器中不允许旋转其界面的视图?

Sta*_*tas 4 iphone objective-c uiinterfaceorientation ios ios6

帮我解决任务 - 我有一个不允许旋转其界面的viewController:

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
Run Code Online (Sandbox Code Playgroud)

但我需要旋转出现在此控制器中的alertView!因此,如果用户旋转设备,则alertView应该跟随旋转并且主界面静止不动.我试图订阅通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotated:) name:UIDeviceOrientationDidChangeNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

但在我的deviceRotated:收到通知中我有这样的负载: NSConcreteNotification 0x101dc50 {name = UIDeviceOrientationDidChangeNotification; object = <UIDevice: 0x103e640>; userInfo = { UIDeviceOrientationRotateAnimatedUserInfoKey = 1; }}

什么是UIDeviceOrientationRotateAnimatedUserInfoKey?我如何使用知道当前的interfaceOrientation?或者建议一种更好的方法来获取当前方向并旋转alertView.

我试着用

(BOOL)shouldAutorotateToInterfaceOrientation:UIInterfaceOrientation)toInterfaceOrientation

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 但这些方法不会在iOS6上调用:(

此外,还有其他方法可以用来知道设备正在旋转到某个方向吗?提前致谢!PS我知道这个任务看起来有点傻,但这是客户的要求.抱歉:)

red*_*t84 5

有一个orientation变量UIDevice包含当前的设备方向.您可以使用它而不是界面方向(不会像您已经注意到的那样旋转).

首先,您订阅了设备方向更改,这是一个好地方viewWillAppear,取消订阅viewWillDisappear:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我们表示我们希望orientationChanged:在设备旋转时调用它,所以让我们实现它:

#pragma mark - Orientation change events
- (void)orientationChanged:(NSNotification*)notification {
    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];

    // Calculate rotation angle
    CGFloat angle;
    switch (deviceOrientation) {
        case UIDeviceOrientationPortraitUpsideDown:
            angle = M_PI;
            break;
        case UIDeviceOrientationLandscapeLeft:
            angle = M_PI_2;
            break;
        case UIDeviceOrientationLandscapeRight:
            angle = - M_PI_2;
            break;
        default:
            angle = 0;
            break;
    }

    // Apply rotation
    static NSTimeInterval animationDuration = 0.3;
    [UIView animateWithDuration:animationDuration animations:^{
        _viewToRotate.transform = CGAffineTransformMakeRotation(angle);
    }];
}
Run Code Online (Sandbox Code Playgroud)