iOSアプリ開発の逆引き辞典

iPhone/iPadで使えるアプリ開発のTipsをまとめてみました

デバイスが回転されたことを検出する

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:
            // iPhoneを縦にして、ホームボタンが下にある状態
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            // iPhoneを縦にして、ホームボタンが上にある状態
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            // iPhoneを横にして、ホームボタンが左にある状態
            break;
            
        case UIDeviceOrientationLandscapeRight:
            // iPhoneを横にして、ホームボタンが右にある状態
            break;
            
        case UIDeviceOrientationFaceUp:
            // iPhoneの液晶面を天に向けた状態
            break;
            
        case UIDeviceOrientationFaceDown:
            // iPhoneの液晶面を地に向けた状態
            break;
            
        case UIDeviceOrientationUnknown:
        default:
            // 向きが分からない状態
            break;
    }
}

UIDeviceOrientation列挙型には、下記のような定義が存在しています。UIDeviceOrientation列挙型については「デバイスの向きを定義するUIDeviceOrientation列挙型 - iOSアプリ開発の逆引き辞典」で詳細に紹介していますので合わせてお読みください。

説明
UIDeviceOrientationPortrait iPhoneを縦にして、ホームボタンが下にある状態
UIDeviceOrientationPortraitUpsideDown iPhoneを縦にして、ホームボタンが上にある状態
UIDeviceOrientationLandscapeLeft iPhoneを横にして、ホームボタンが左にある状態
UIDeviceOrientationLandscapeRight iPhoneを横にして、ホームボタンが右にある状態
UIDeviceOrientationFaceUp iPhoneの液晶面を天に向けた状態
UIDeviceOrientationFaceDown iPhoneの液晶面を地に向けた状態
UIDeviceOrientationUnknown 向きが分からない状態

参考