LoginSignup
29
33

More than 1 year has passed since last update.

iOS でデバイスの向きを取得するときの罠

Last updated at Posted at 2014-10-16

よくやるやつ

デバイスの向きを取得する場合、下記のようなコードをよく見かけます。

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
switch (orientation) {
    case UIInterfaceOrientationPortrait:
        break;
    default:
        break;
}

一見大丈夫そうなんですが、実はこれだとenum の値が0で返ってくることがあります。
手元で確認した限りでは、シミュレータとテーブルの上に水平においたデバイスの両方で再現しました。
つまり上の例だと、実際はPortraitとして認識してほしいのにdefaultの方に処理が流れちゃうことがあります。

おーこわ。

[[UIApplication sharedApplication] statusBarOrientation] を使おう

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
switch (orientation) {
    case UIInterfaceOrientationPortrait:
        break;
    default:
        break;
}

詳しいことはわかりませんが、これで無事、正しい向きが取得できました。

参考

2022/12/02 追記

statusBarOrientation は非推奨になっています。
https://developer.apple.com/documentation/uikit/uiapplication/1623026-statusbarorientation

Use the interfaceOrientation property of the window scene instead.

とあるので、そっちを使いましょう。(未確認)

29
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
33