【Xcode】アプリ画面の向きを固定する方法!デバイスの回転と縦横識別

この記事からわかること
- Xcodeでアプリの画面の向きを固定する方法
- デバイスの回転を制御する
- PortraitやLandscapeとは?
- デバイスの向き(縦/横/上向き)を取得するには?
index
[open]
\ アプリをリリースしました /
iOSアプリをリリースした際にデバイスを横にした時に画面が崩れてしまったので、画面を回転させてもアプリ画面の向きが変化しないように設定していきたいと思います。

環境
- Xcode:14.2
アプリ画面の向きを固定する方法
Xcodeでアプリの画面の向きを固定するには「TARGETS」>「Deployment Info」>「Device Orientation(デバイスの向き)」から設定可能です。「Device Orientation(デバイスの向き)」ではアプリに許容させたい向きを指定する設定項目なのでアプリ画面の向きを縦向きのみに固定するにはPortrait
のみにチェックを入れます。

許容する向きの設定値
- Portrait:縦向き
- Upside Down:逆さま(※)
- Landscape Left:左向き
- Landscape Right:右向き
※Upside Down:逆さまに関してはチェックを入れてもアプリ画面が逆さまにはなりませんでした。(2023年6月現在)
英語の意味
- Orientation(オリエンテーション):1.適応(指導) 2.方向
- Portrait(ポートレート):1.肖像画 2.印刷用紙の縦置き
- Landscape(ランドスケープ):1.風景・景色 2.印刷用紙の横置き
iPadでのデバイスの回転
「Device Orientation(デバイスの向き)」は「iPhone Orientation」と「iPad Orientation」に分かれているのでiPadにも画面の向きを適応させたい場合は「iPad Orientation」側のチェックを設定します。
※Upside Down:iPad側では正常に動作しました。(2023年6月現在)
info.plistから設定する
Xcodeの「info.plist」からでもアプリ画面の向きを設定することが可能です。「info.plist」に設定するためのキー「Supported interface orientations (iPhone)」を指定し、値(value)には先ほどと似たような設定値を渡します。

許容する向きの設定値
- Portrait(top home button):縦向き
- Portrait(top home button):逆さま
- Landscape(left home button):左向き
- Landscape(right home button):右向き
先ほどの「Device Orientation」と「Supported interface orientations (iPhone)」はリンクしているようなのでどちらかの設定をいじるともう片方も自動で修正されます。(info.plist側は削除される)
現在の画面の向きを取得する
デバイス現在の向きをコードで取得するにはUIDevice
クラスのorientation
プロパティを参照します。
UIDevice.current.orientation
取得できるのはUIDeviceOrientation
型で値はデバイスが水平で画面が上向きのfaceUp
や不明(unknown
)などを追加した7種類定義されています。
func printOrientation(){
let orientation:UIDeviceOrientation = UIDevice.current.orientation
switch orientation{
case .unknown:
print("デバイスの向きが不明")
case .portrait:
print("デバイスの向きが縦向き")
case .portraitUpsideDown:
print("デバイスの向きが逆さま")
case .landscapeLeft:
print("デバイスの向きが左向き")
case .landscapeRight:
print("デバイスの向きが右向き")
case .faceUp:
print("デバイスが水平で画面が上向き")
case .faceDown:
print("デバイスが水平で画面が下向き")
default:
break
}
}
デバイスの向き変更を検知/取得する方法
デバイスの回転を検知するためにはNotificationCenter
クラスを使用します。
func observerOrientation(){
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(
forName: UIDevice.orientationDidChangeNotification,
object: nil,
queue: nil) { orientation in
print("デバイスの向きが変わったよ")
}
}
func stopObserver(){
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。
個人開発に限界を感じたらiOSに特化したプログラミングスクール「iOSアカデミア」も検討してみてください!無料相談可能で「最短・最速」でiOSエンジニアになれるように手助けしてくれます。