LoginSignup
1
0

More than 5 years have passed since last update.

iOS端末の向き

Last updated at Posted at 2018-05-07

端末がロックされていた場合の向きの取り方
モーションセンサーを使えば行けました!

    let motion = CMMotionManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        motion.accelerometerUpdateInterval = 1.0;

        motion.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:

            { (data, error) in
                self.getOrientation( x:(data?.acceleration.x)!, y:(data?.acceleration.y)! )
            })
    }

    func getOrientation(x: Double, y: Double) {
        if (fabs(x) < 0.5) {
            if (y < 0) {
                print( "right" )

            } else {
                print( "left" )

            }
        } else {
            if (x < 0) {
                print( "up" )
            } else {
                print( "down" )
            }
        }
    }

これで全部のパターンで向き取れたのはいんだけど。

端末側で向きがロックされてたら取れないね・・・
ロックされてても回転方向知りたいorz ボスケテ

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.onOrientationDidChange(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }

    @objc func onOrientationDidChange(notification: NSNotification) {

        switch UIDevice.current.orientation {
        case .faceDown:
            print("Face down")
        case .faceUp:
            print("Face up")
        case .unknown:
            print("Unknown")
        case .landscapeLeft:
            print("Landscape left")
        case .landscapeRight:
            print("Landscape right")
        case .portrait:
            print("Portrait")
        case .portraitUpsideDown:
            print("Portrait upside down")
        }
    }
1
0
2

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