2013-08-26 8 views
5

私のアプリでは、Amazonの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)あなたがする必要がある残りのすべては、ロック可能にしたいView Controllerのオーバーライドされたメソッドです(ios 6+ 、supportedInterfaceOrientations)。あなたの保存されたユーザーのデフォルトを使用して、あなたがロックされているかどうかに基づいてあなたが可能にする向きを返します。

その後、再び彼らのメソッドを呼び出すと、彼らは機器与えられた現在の回転であるべき回転再評価するためにあなたのビューコントローラを言うとattemptRotationToDeviceOrientation を呼び出します。

+0

ありがとう、tryRotationToDeviceOrientationはトリックを行います。 – 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

これはまさに私が求めていた質問ではありません。すでに私が行っていた回転ロックの実装方法を尋ねていませんでした。回転ロックが解除されたときにデバイスの向きに回転する方法を尋ねていました。私はすべてのことを行う方法を尋ねたが、彼は私の実際の質問に答えました - UIViewControllerクラスメソッドのtryRotationToDeviceOrientationは私が必要としていたものでした。 – dysfunction

関連する問題