iPhoneの向きを特定するもう一つの方法

こんにちは、@yoheiMuneです。
今日は、iPhoneバイスの向きを特定する方法を。
UIViewControllerのshouldAutorotateToInterfaceOrientationメソッド以外でも、特定する方法を学んだので、ブログに残しておきたいと思います。



UIDeviceとNSNotificationCenterを使って、デバイスの向きの変化を感知する

やり方は凄くカンタン!UIDeviceで向きの変化を感知を開始して、向きの変化があったらNSNotificationCenterに向きの変化を感知させる。こーするだけで、向きの変化を感知することが出来るようです。
以下がサンプルコートです。

- (void)viewDidLoad {
  [super viewDidLoad];
	
  // start monitoring device orientation changes.
  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  [[NSNotificationCenter defaultCenter] addObserver:self 
                                                                   selector:@selector(didRotate:) 
                                                                       name:UIDeviceOrientationDidChangeNotification 
                                                                      object:nil];
}

ここでは、viewがロードされたタイミングで、UIDeviceのbeginGeneratingDeviceOrientationNotificationsメソッドを読み出し、向きの変化の監視を始めます。
そして、NSNotificationCenterに、UIDeviceOrientationDidChangeNotificationを監視させるオブザーバーを追加し、向きの変化をとらえると、selfのdidRotate:メソッドを呼び出すように指定しています。

didRotate:メソッドの実装例は以下です。

- (void) didRotate:(NSNotification *)notification {
  UIDeviceOrientation orientation = [[notification object] orientation];

  if (orientation == UIDeviceOrientationPortrait) {
    label1.text = @"device orientation is Portrait.";

  } else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
    label1.text = @"device orientation is Portrait Upside Down.";	

  } else if (orientation == UIDeviceOrientationLandscapeLeft) {
    label1.text = @"device orientation is Landscape Left.";

  } else if (orientation == UIDeviceOrientationLandscapeRight) {
    label1.text = @"device orientation is Landscape Right.";

  } else if (orientation == UIDeviceOrientationFaceUp) {
    label1.text = @"device orientation is Face Up."	

  } else if (orientation == UIDeviceOrientationFaceDown) {
    label1.text = @"device orientation is Face Down.";

  } else {
    label1.text = @"device orientation is Unkown.";
  }
}

didRote:メドッドは引数にNSNotificationを貰うようにしてあります。NSNotificationからUIDeviceOrientationを取得し、その値を見る事で、デバイスの向きを特定出来ます。UIDeviceOrientationの取りうる値は以下の通りです。

UIDeviceOrientationPortrait 立て向きで、ホームボタンは下
UIDeviceOrientationUpsideDown 立て向きで、ホームボタンが上
UIDeviceOrientationLandscapeLeft 横向きで、ホームボタンが右
UIDeviceOrientationLandscapeRight 横向きで、ホームボタンが左
UIDeviceOrientationFaceUp 画面が上向き
UIDeviceOrientationFaceDown 画面が下向き
UIDeviceOrientationunKnown 画面の向きが分からない

参考サイト

以下のサイトを参考にしました。詳しくは、以下リファレンスをご参照ください。
UIDevice Class Reference
NSNotificationCenter Class Reference



最後に

バイス向きの変化をとらえるのは、shouldAutorotateToInterfaceOrientationだけかと思っていましたが、調べると他にもあるものなんですね。
他にも色々と便利な機能を知ると、より楽にアプリ開発が出来るようになりそうだなぁ(*´∇`*)
以下は、関連ページです。ご参考になれば幸いです。