hachinoBlog

hachinobuのエンジニアライフ

端末の向きの取得方法

縦画面、横画面に応じてレイアウトの変更などが必要な場合に端末の現在の向きを取得したい場合が多々ある。

そんな時には下記のように取得する。

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

viewWillAppearで取得して、その値をwillRotateToInterfaceOrientationやdidRotateFromInterfaceOrientationの引数にして縦か横か判断してレイアウトをいじる方法をよく使っています。

サンプルコード

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //現在の向きを表すUIInterfaceOrientation取得
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    //向きに応じてレイアウトを設定する
    [self willRotateToInterfaceOrientation:orientation duration:.0f];
    //設定したレイアウトを反映する
    [self didRotateFromInterfaceOrientation:orientation];
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    //縦画面
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
        //縦画面に応じたViewの座標やサイズなどレイアウトを設定する
        return;
    }
    
    //横画面に応じたViewの座標やサイズなどレイアウトを設定する
    
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    //willRotateToInterfaceOrientationで設定したレイアウトを反映する
}

willRotateToInterfaceOrientationで設定したレイアウトを反映する処理を書いてもうまくいかなかったのでdidRotateFromInterfaceOrientationのタイミングでレイアウトを反映するようなコードになっています。