よくやるやつ
デバイスの向きを取得する場合、下記のようなコードをよく見かけます。
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.
とあるので、そっちを使いましょう。(未確認)