デバイスの向きによって、UI部品のサイズやデザインを変更したいということもありますよね。
そこで、今回はデバイスの向きが変わったことを検知する方法を紹介します。
デバイスの向きに関する基礎知識
デザインの向きのことをorientatation(オリエンテーション)と呼びます。
そして、縦向きのことを「portrait(ポートレート)」、横向きのことを「landscape(ランドスケープ)」と呼ぶので、知っておきましょう。
画面の向きが変わったことを検知するためのコード
画面の向きを検知するには次のように書きます。
import UIKit
class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    //画面の向きが変わったことを通知する
     NotificationCenter.default.addObserver(
          self,
          selector: #selector(self.changedOrientation),
          name: UIDevice.orientationDidChangeNotification,
          object: nil)
  }
  // 画面の向きが変わった時に呼ばれる
   @objc func changedOrientation() {
      print("画面の向きが変わった")
  }
}これで画面の向きが変わるたびに、changedOrientation()が呼ばれるようになります。
現在の向きを取得する方法
現在の画面が縦向きか横向きかを判別したい場合、UIDevice.current.orientationを使います。
縦向きかどうかを判別する
if UIDevice.current.orientation.isPortrait {
  print("縦向きです")
}横向きかどうかを判別する
if UIDevice.current.orientation.isLandscape {
  print("横向きです")
}

