2013-08-26 77 views
5

我在我的应用程序中实现了一个类似于亚马逊Kindle应用程序中的编程旋转锁:当设备旋转时,锁按钮显示;按下按钮并且方向锁定到按下按钮时界面所在的方向。解锁编程旋转锁后强制iOS ViewController旋转到设备方向

解锁后,我想界面旋转到当前的设备方向。假设您锁定纵向旋转,将设备旋转至左侧,然后解锁;我想让界面旋转到左侧。这里是切换锁的方法:

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

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

然后致电attemptRotationToDeviceOrientation 告诉您的视图控制器再次调用他们的方法,并重新评估它们应该在给定设备当前旋转时的旋转角度。

+0

谢谢,attemptRotationToDeviceOrientation做的伎俩! – dysfunction

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; 
} 
+0

这不完全是我问的问题 - 我没有问如何实现旋转锁定,我已经完成了,我正在问旋转锁定解锁时如何旋转到设备方向。它看起来像atomk也认为我问如何做的整个事情,但他没有回答我的实际问题 - UIViewController类方法attemptRotationToDeviceOrientation是我所需要的。 – dysfunction