Swift3で画面の向き変更を通知する
今回の目標
画面の向きが変更された場合にその変更を検知する
開発環境
- Xcode:8.2.1
- 言語:Swift 3
- OS:MacOS
画面の向き変更の通知のやり方
通知メソッドの中に端末の向きが変更された際に呼び出すもの(UIDeviceOrientationDidChange
)があるので、それを利用します
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
// #selectorで通知後に動く関数を指定。name:は型推論可(".UIDeviceOrientationDidChange")
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.changeDirection), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
func changeDirection(notification: NSNotification){
print("向きが変更されました")
}