Question

I would like to make a custom orientation lock button for a reader app of mine, and I was thinking it wouldn't be too bad to whip up, but alas I am the one getting whipped.

To start off I do have this method:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
 }

And then I was thinking that I could handle the actual locking in an action method like this:

- (IBAction) screenLock:(id)sender{

if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait){

    [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];

}else{

            [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

}

  }

But alas, this code will not hold sway over the former that instructs the view to rotate...

Am I going about this all wrong? What is a better way to do it? I just want to have local, easy way to have my users lock the orientation of their screen. I guess it would be using a boolean value where they hit a button to lock and then hit again to unlock...

Thoughts? Thanks!!

Was it helpful?

Solution

shouldAutorotateToInterfaceOrientation ripples up your view hierarchy so your logic needs to be put into your app delegate (or as the most senior ViewController that might return YES). Put a BOOL property in your appDelegate and set it via your lock button (e.g. target pointers/delegates (AppDelegate)) then in your appDelegate do something like this:

#define ROTATION_MASTER_ENABLED 1

//Setting MASTER_ROTATION_LOCK_ENABLED to 0 will stop the device rotating
//Landscape UP>landscape DOWN and Portrait UP>Portrait DOWN, 
//This is not generally desired or app store safe, default = 1

-(BOOL)compareOrientation:(UIInterfaceOrientation)interfaceOrientation
{

    UIInterfaceOrientation actual = [[UIDevice currentDevice] orientation]; 
    if(UIInterfaceOrientationIsLandscape(interfaceOrientation) && UIInterfaceOrientationIsLandscape(actual))return YES; 
    else if(UIInterfaceOrientationIsPortrait(interfaceOrientation)&& UIInterfaceOrientationIsPortrait(actual))return YES;
    else return NO;   

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{   
    if(!MASTER_ROTATION_LOCK_ENABLED)return NO;
    else if(self.rotationEnabled || [self compareOrientation:interfaceOrientation])return YES;
    return NO;//self.rotationEnabled is a BOOL
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top