iOS device orientation disregarding orientation lock

后端 未结 10 1317
天涯浪人
天涯浪人 2020-11-29 01:59

I want to query the orientation the iPhone is currently in. Using

[UIDevice currentDevice].orientation

works as long as the device isn\'t

10条回答
  •  不知归路
    2020-11-29 02:33

    Also you can use CoreMotion

    Orientation detection algorithm:

    • if abs( y ) < abs( x ) your iPhone is in landscape position, look sign of x to detect right or left

    • else your iPhone is in portrait position, look sign of y to detect up or upside-down.

    • If you are interested in face-up or down, look value of z.


    import CoreMotion
    

    var uMM: CMMotionManager!
    
    override func
    viewWillAppear( p: Bool ) {
        super.viewWillAppear( p )
        uMM = CMMotionManager()
        uMM.accelerometerUpdateInterval = 0.2
    
        //  Using main queue is not recommended. So create new operation queue and pass it to startAccelerometerUpdatesToQueue.
        //  Dispatch U/I code to main thread using dispach_async in the handler.
        uMM.startAccelerometerUpdatesToQueue( NSOperationQueue() ) { p, _ in
            if p != nil {
                println(
                    abs( p.acceleration.y ) < abs( p.acceleration.x )
                    ?   p.acceleration.x > 0 ? "Right"  :   "Left"
                    :   p.acceleration.y > 0 ? "Down"   :   "Up"
                )
            }
        }
    }
    
    override func
    viewDidDisappear( p: Bool ) {
        super.viewDidDisappear( p )
        uMM.stopAccelerometerUpdates()
    }
    

提交回复
热议问题