即使设备的方向已锁定,也可以获取当前iOS设备的方向 [英] Get current iOS device orientation even if device's orientation locked
本文介绍了即使设备的方向已锁定,也可以获取当前iOS设备的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使设备的方向已锁定,我也要获取当前的iOS设备方向. (就像iOS相机应用一样)
I want to get the current iOS device orientation even if device's orientation is locked. (Just like iOS Camera app)
我想至少检测人像,左横向和右横向.
I want to detect Portrait, Landscape Left and Landscape Right at least.
锁定方向后,UIDeviceOrientation和UIInterfaceOrientation似乎不起作用.
UIDeviceOrientation and UIInterfaceOrientation do not seem to work when orientation is locked.
在这种情况下,我认为我们将使用CoreMotion.
In this case, I think that we will use CoreMotion.
我如何在swift4中对其进行逻辑处理?
How do i logic it in swift4?
推荐答案
使用核心运动声明运动管理器
var orientationLast = UIInterfaceOrientation(rawValue: 0)!
var motionManager: CMMotionManager?
运动管理器初始化
并在viewDidLoad中调用此函数
and call this function in viewDidLoad
func initializeMotionManager() {
motionManager = CMMotionManager()
motionManager?.accelerometerUpdateInterval = 0.2
motionManager?.gyroUpdateInterval = 0.2
motionManager?.startAccelerometerUpdates(to: (OperationQueue.current)!, withHandler: {
(accelerometerData, error) -> Void in
if error == nil {
self.outputAccelertionData((accelerometerData?.acceleration)!)
}
else {
print("\(error!)")
}
})
}
要分析加速度计的仪表数据
func outputAccelertionData(_ acceleration: CMAcceleration) {
var orientationNew: UIInterfaceOrientation
if acceleration.x >= 0.75 {
orientationNew = .landscapeLeft
print("landscapeLeft")
}
else if acceleration.x <= -0.75 {
orientationNew = .landscapeRight
print("landscapeRight")
}
else if acceleration.y <= -0.75 {
orientationNew = .portrait
print("portrait")
}
else if acceleration.y >= 0.75 {
orientationNew = .portraitUpsideDown
print("portraitUpsideDown")
}
else {
// Consider same as last time
return
}
if orientationNew == orientationLast {
return
}
orientationLast = orientationNew
}
这篇关于即使设备的方向已锁定,也可以获取当前iOS设备的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文