Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

よくやるやつ

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

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;
}

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

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away