Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
dysfunction Avatar asked Nov 01 '22 16:11

dysfunction


1 Answers

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.

like image 63
atomkirk Avatar answered Nov 09 '22 09:11

atomkirk