解锁程序化旋转锁后,强制iOS视图控制器旋转到设备方向

5
我正在实现一个编程式的旋转锁,类似于亚马逊Kindle应用中的锁定功能:当设备被旋转时,会显示一个锁定按钮;按下按钮后,方向将锁定到按下按钮时界面所在的方向。
解锁后,我希望界面能旋转到当前设备的方向。比如你锁定了竖屏方向,将设备旋转到左横屏,然后解锁;我希望界面能旋转到左横屏。以下是切换锁定的方法:
- (IBAction)toggleRotationLock:(UIButton *)sender {
BOOL rotationLocked = [_defaults boolForKey:@"RotationLocked"];
if (rotationLocked) {   //unlock rotation
    [_defaults setBool:NO forKey:@"RotationLocked"];
    /* force rotation to current device orientation here?
     * ...
     */
} else {    //lock rotation to current orientation
    [_defaults setBool:YES forKey:@"RotationLocked"];
    [_defaults setInteger:self.interfaceOrientation forKey:@"RotationOrientation"];
}
    [_defaults synchronize];
    [self setupRotationLockButton];
}

有什么方法可以做到这一点吗?
2个回答

2
关键是:1)像你现在做的那样,将当前方向保存到用户默认设置中;2)你需要做的其他所有事情都在你想要锁定的视图控制器的重写方法中(对于iOS 6+,使用supportedInterfaceOrientations)。根据是否锁定,使用保存的用户默认设置返回允许的方向。
然后调用attemptRotationToDeviceOrientation,告诉你的视图控制器再次调用它们的方法,并重新评估给定设备当前旋转应该处于什么旋转。

0
这是我让它工作的方式,以防万一有人想查看代码。 :)
-(IBAction)lockOrientation:(UIButton*)sender
{
if (orientationLocked) { //Unlock it, "orientationLocked" is a boolean defined in .h
    orientationLocked = NO;
    [sender setTitle:@"Unlocked" forState:UIControlStateNormal];
}
else
{ // Lock it.

    //Save the orientation value to NSDefaults, can just be int if you prefer.
    // "defaults" is a NSUserDefaults also defined in .h

    [defaults  setInteger:[[UIApplication sharedApplication] statusBarOrientation] forKey:@"orientation"];
    orientationLocked = YES;
    [sender setTitle:@"Locked" forState:UIControlStateNormal];
}
} 

- (NSUInteger)supportedInterfaceOrientations{
if (orientationLocked) {

    return = [defaults integerForKey:@"orientation"];
}
return UIInterfaceOrientationMaskAllButUpsideDown;
}

这并不是我要问的问题 - 我不是在问如何实现旋转锁定,因为我已经做过了,我想知道的是当旋转锁定解除时如何旋转到设备方向。看起来atomk也认为我在问如何完成整个操作,但他确实回答了我的实际问题 - UIViewController类方法attemptRotationToDeviceOrientation就是我所需要的。 - dysfunction

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接