目的
iOSアプリで端末の向きの変更を検知する処理のメモ
検知の方法を載せているサイトは多いですが、どれも古いバージョンでした
ここではswift5のメモです。
環境
- Xcode 11.2.1
- swift 5
実装メモ
向きが変わると背景色が変わるようにしました。
横向きだと赤、縦向きだと青になります。
コードは以下だけです。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChange), name: UIDevice.orientationDidChangeNotification, object: nil)
}
@objc
func onOrientationChange(notification: NSNotification){
let deviceOrientation: UIDeviceOrientation! = UIDevice.current.orientation
if deviceOrientation.isLandscape {
self.view.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
} else if deviceOrientation.isPortrait{
self.view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
}
}
}
動き
実際の動きは以下のようになります。
シミュレーターでショートカットキーで向きを変えています。