2013-01-17 7 views
14

UIViewControllerへのポインタがある場合、コントローラのコードを変更せずにinterfaceOrientationを変更したときに通知を受けることはできますか?UIViewControllerがinterfaceOrientationを変更したときを観察できますか?

デバイスの向きの変化を検出し、UIViewControllerが回転するかどうかを確認するのが最善でしょうか(d)?

+0

質問がまだ実際であるかどうかはわかりませんが、objcメソッドを使って「UIViewController」のコードに独自のコードを追加することができます。これは '-didRotateFromInterfaceOrientation:'と向きを変えたハンドラメソッドの呼び出しと元の実装への呼び出しを持つ独自の実装と交換するように見えるはずです – medvedNick

+0

@medvedNickそれは妥当と思われます。私は代理人に電話をして、元の実装を呼び出すことができました。潜在的な副作用が少し気になるかもしれません。 –

答えて

16

あなたはNSNotificationCenterを使用することができます。

[[NSNotificationCenter defaultCenter] addObserver:self // put here the view controller which has to be notified 
             selector:@selector(orientationChanged:) 
              name:@"UIDeviceOrientationDidChangeNotification" 
              object:nil]; 
- (void)orientationChanged:(NSNotification *)notification{ 
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

    //do stuff 
    NSLog(@"Orientation changed");   
} 
+3

Hmm。私は明らかではないと思う。私は、デバイスではなくViewControllerの見かけの向きを知りたい。言い換えれば、私のオブジェクトは、デバイスの姿勢を見るためにビューコントローラを観察したいと思っています。デバイスの向きが変わっても変化しないかもしれません。この回答は、私が質問の第2部分に含意していたものの一部です。 –

2

あなたののUIViewControllerにwillAnimateRotationToInterfaceOrientation:duration:メソッドを使用して、風景や肖像画のために任意のUIViews(またはその他のコード)を再配置することができます。例えば。

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 
    // change positions etc of any UIViews for Landscape 
    } else { 
    // change position etc for Portait 
    } 

    // forward the rotation to any child view controllers if required 
    [self.rootViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; 
} 
+1

残念ながら、これはUIViewControllerのコードを変更することを意味します。ここで私はそれへのポインタしか持っておらず、その振る舞いを観察したい。 "interfaceOrientation"が別の値を返すとき、本当にやりたいことは通知されます。 –

+0

注意:これはiOS 8では非推奨です。http://stackoverflow.com/questions/25238620/ios-8-rotation-methods-deprecation-backwards-compatibility – jowie

関連する問題