iPhone/iPadアプリでデバイスを回転させて横向きにすると、より詳細にデータ表示したい時があります。デバイスを回転されたのとトリガーにして
デバイスが回転されたかの監視を開始する
UIDeviceクラスのインスタンスのbeginGeneratingDeviceOrientationNotificationsメソッド
を実行することで、センサーデバイスの有効にして加速度の変化の配信を開始します。
アプリ側でデバイスの向きの変化を受信する為には、通知センターにUIDeviceOrientationDidChangeNotification通知
が発生した時に通知してもらえるように登録します。
-(void)viewDidAppear:(BOOL)animated
{
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(didChangedOrientation:)
name:UIDeviceOrientationDidChangeNotification object:nil];
}
デバイスが回転されたかの監視を終了する
通知を受け取るのを止める時には、通知センターから通知を受けるのを解除します。合わせてセンサーデバイスからの通知を止めてしまいましょう。
- (void)viewDidDisappear:(BOOL)animated
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self
name:UIDeviceOrientationDidChangeNotification object:nil];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}
デバイスが回転された通知を受け取る
前述のサンプルコードでは、デバイスの向きを変更するとdidChangedOrientation:メソッド
に通知がくるように通知センターへ登録しました。
通知センターからはNSNotificationクラスで通知されてくるのでobject
プロパティ、さらにorientation
プロパティを取得するとデバイスの向きを定義するUIDeviceOrientation列挙型の値を取得することができます。
- (void)didChangedOrientation:(NSNotification *)notification
{
UIDeviceOrientation orientation = [[notification object] orientation];
switch (orientation) {
case UIDeviceOrientationPortrait:
break;
case UIDeviceOrientationPortraitUpsideDown:
break;
case UIDeviceOrientationLandscapeLeft:
break;
case UIDeviceOrientationLandscapeRight:
break;
case UIDeviceOrientationFaceUp:
break;
case UIDeviceOrientationFaceDown:
break;
case UIDeviceOrientationUnknown:
default:
break;
}
}
UIDeviceOrientation列挙型には、下記のような定義が存在しています。UIDeviceOrientation列挙型については「デバイスの向きを定義するUIDeviceOrientation列挙型 - iOSアプリ開発の逆引き辞典」で詳細に紹介していますので合わせてお読みください。
値 |
説明 |
UIDeviceOrientationPortrait |
iPhoneを縦にして、ホームボタンが下にある状態 |
UIDeviceOrientationPortraitUpsideDown |
iPhoneを縦にして、ホームボタンが上にある状態 |
UIDeviceOrientationLandscapeLeft |
iPhoneを横にして、ホームボタンが左にある状態 |
UIDeviceOrientationLandscapeRight |
iPhoneを横にして、ホームボタンが右にある状態 |
UIDeviceOrientationFaceUp |
iPhoneの液晶面を天に向けた状態 |
UIDeviceOrientationFaceDown |
iPhoneの液晶面を地に向けた状態 |
UIDeviceOrientationUnknown |
向きが分からない状態 |
参考