iOS使用陀螺仪判断屏幕方向
2018-08-28 本文已影响242人
咸鱼有只喵
当需要判断屏幕方向时,我们通常使用UIDevice或者statusBar,但是还有一种方法就是使用陀螺仪来进行判断。上代码:
初始化motionManager和timer计时器
let motionManager = CMMotionManager()
var timer: Timer!
motionManager.startAccelerometerUpdates()
motionManager.startGyroUpdates()
motionManager.startMagnetometerUpdates()
motionManager.startDeviceMotionUpdates()
//注册timer监听
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
update函数实现
@objc func update() {
if let accelerometerData = motionManager.accelerometerData {
print(accelerometerData)
}
if let gyroData = motionManager.gyroData {
print(gyroData)
}
if let magnetometerData = motionManager.magnetometerData {
print(magnetometerData)
}
var result = "unknow"
if let motion = motionManager.deviceMotion {
//print(deviceMotion)
let x = motion.gravity.x
let y = motion.gravity.y
if fabs(y) >= fabs(x) {
if y >= 0 {
result = "updown"
// UIDeviceOrientationPortraitUpsideDown;
} else {
result = "updown"
// UIDeviceOrientationPortrait;
}
} else {
if x >= 0 {
result = "right"
// UIDeviceOrientationLandscapeRight;
} else {
result = "left"
// UIDeviceOrientationLandscapeLeft;
}
}
print(result)
}
}