LoginSignup
1
0

More than 1 year has passed since last update.

デバイスの傾きを検知して向きによって決めた処理をさせる。(UIDevice)

Posted at

今回の内容

  • デバイス(iPhone自体)を傾けた時に、傾けた事を検知して傾けた向きによって処理をさせる。

コードと簡単解説

  • まずは、UIDevice.current.beginGeneratingDeviceOrientationNotifications()でデバイスを回転させた時の検知を始める。
  • デバイスの向きが変わった時、変わった向きによってmapViewframeを対応させる。(縦長にしたり横長にしたりって感じです)
           ~~~一部省略~~~

     @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で面白そうなプロパティがあったので試してみたいです。
ご指摘、ご質問などありましたら、コメントまでお願い致します。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0