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

有什么办法可以做到这一点?

4

2 回答 2

2

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

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

于 2013-08-26T02:19:45.130 回答
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;
}
于 2013-08-26T05:28:31.830 回答