解锁编程旋转锁定后,强制iOS ViewController旋转到设备方向



我正在我的应用程序中实现一个类似于亚马逊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];
}

有办法做到这一点吗?

关键是1)将当前方向保存为用户默认值,就像您所做的那样2)您需要做的所有其他事情都在您想要锁定的视图控制器的重写方法中(对于ios 6+,supportedInterfaceOrientations)。使用您保存的用户默认值返回您允许的方向,基于它是否被锁定。

然后呼叫attemptRotationToDeviceOrientation告诉视图控制器再次调用它们的方法,并在给定设备当前旋转的情况下重新评估它们应该处于的旋转。

这就是我让它工作的方式,以防有人来这里查看代码。:)

-(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;
}

最新更新