Search code examples
iphoneiosobjective-cios5ios6

Force iOS ViewController to rotate to device orientation after unlocking programmatic rotation lock


I'm implementing a programmatic rotation lock in my app similar to that found in Amazon's Kindle app: when the device is rotated, a lock button shows; press the button and the orientation is locked to the orientation the interface was in when the button was pressed.

After unlocking, I'd like to have the interface rotate to the current device orientation. Say you lock rotation in portrait, rotate the device to landscape left, and then unlock; I'd like the interface to then rotate to landscape left. Here's the method that toggles the lock:

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

Any way to do this?


Solution

  • The key is 1) saving the current orientation to user defaults exactly like youre doing 2) all the rest of what you need to do is in your overridden methods of the view controllers you want to be lockable (for ios 6+, supportedInterfaceOrientations). Use your saved user defaults to return what orientations youre allowing based on if its locked or not.

    Then call attemptRotationToDeviceOrientation To tell your view controllers to call their methods again and reevaluate what rotation they should be in given the devices current rotation.