答案 0 :(得分:0)
所有要做的就是像这样锁定设备方向:
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
和:
override var shouldAutorotate: Bool {
return false
}
已完成一项操作-使用CoreMotion检测手机方向: 1.设置设备运动检测:
func startDeviceMotion() {
if motion.isDeviceMotionAvailable {
self.motion.deviceMotionUpdateInterval = 10.0 / 60.0
self.motion.showsDeviceMovementDisplay = true
self.motion.startDeviceMotionUpdates(using: .xMagneticNorthZVertical)
self.timer = Timer(fire: Date(), interval: (10.0/60.0), repeats:
true,block: { (timer) in
self.deviceRotated()
})
RunLoop.current.add(self.timer!, forMode: .defaultRunLoopMode)
}
}
手柄旋转:
func deviceRotated() {
if let deviceMotion = motion.deviceMotion {
let degree = deviceMotion.attitude.roll * 180 / .pi
print(degree)
switch degree {
case -40 ... 40:
UIApplication.shared.statusBarOrientation = .portrait
break
case 50 ... 130:
UIApplication.shared.statusBarOrientation = .landscapeLeft
break
case -130 ... -50:
UIApplication.shared.statusBarOrientation = .landscapeRight
break
default:
break
}
} }
注意:在每个方向上,我都更改了设备状态栏的方向,但是将设备锁定在纵向。 由于我使用代码运动来检测设备旋转的变化-即使最终用户将锁定设备旋转,该解决方案也可以很好地工作。