今回の内容
- デバイス(iPhone自体)を傾けた時に、傾けた事を検知して傾けた向きによって処理をさせる。
コードと簡単解説
- まずは、
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
でデバイスを回転させた時の検知を始める。 - デバイスの向きが変わった時、変わった向きによって
mapView
のframe
を対応させる。(縦長にしたり横長にしたりって感じです)
~~~一部省略~~~
@IBOutlet weak var mapView: MKMapView!
let device = UIDevice.current
override func viewDidLoad() {
super.viewDidLoad()
device.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(devicOrientationDetection), name: UIDevice.orientationDidChangeNotification, object: nil)
~~~一部省略~~~
}
@objc func devicOrientationDetection(){
switch UIDevice.current.orientation{
case .portrait:
mapView.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + self.view.safeAreaInsets.top, width: self.view.frame.size.width, height: self.view.frame.size.height - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top)
case .portraitUpsideDown:
mapView.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + self.view.safeAreaInsets.top, width: self.view.frame.size.width, height: self.view.frame.size.height - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top)
case .landscapeLeft:
mapView.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + self.view.safeAreaInsets.top, width: self.view.frame.size.width, height: self.view.frame.size.height - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top)
case .landscapeRight:
mapView.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY + self.view.safeAreaInsets.top, width: self.view.frame.size.width, height: self.view.frame.size.height - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top)
default:
print("取得出来ませんでした")
}
}
終わり
検知自体はそこまで難しくは無いですね。
あとは、何を処理させるかですね。
まだ、UIDeviceで面白そうなプロパティがあったので試してみたいです。
ご指摘、ご質問などありましたら、コメントまでお願い致します。