比在func外使用var跟踪设备方向更好的方法吗?
问题描述:
注意:这里寻找的非特定解决方案是如何在屏幕尺寸没有改变的情况下避免触发代码,例如,在Y轴上翻转iPad(从landscapeLeft到landscapeRight),向没有调整大小的用户显示视图。换句话说,视图将旋转而不调整任何大小)。该测试实质上验证了不发生向不同方向的中间旋转。比在func外使用var跟踪设备方向更好的方法吗?
我正在研究一个地图应用程序,并希望在方位之间切换时保持缩放级别不变。然而,当不支持纵向颠倒的时候,这种错误就会出现,这是我想用手机的方式,而不是用iPad(没有任何问题)。
当我在纵向和横向之间旋转设备并返回时,没有问题。但是从横向模式旋转到纵向颠倒不会触发viewWillTransition。因此,从那里旋转到相反的风景模式(例如,landscapeLeft> portraitUpsideDown> landscapeRight)会触发viewWillTransition的调用,并将地图的当前高度再乘以aspectRatio,从而导致缩小。
为了解决这个问题,我在func外部创建了一个全局变量,并将其设置为保留以前的方向。此代码工作正常。但如果有更好的方法比使用全局变量我想学习。
var previousOrientation = ""
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
var newOrientation = "";
switch UIDevice.current.orientation{
case .portrait:
newOrientation="Portrait"
case .landscapeLeft, .landscapeRight:
newOrientation="Landscape"
default:
newOrientation="Portrait"
}
if newOrientation == previousOrientation {return}
else{ previousOrientation = newOrientation}
let bounds = UIScreen.main.nativeBounds // alway related to portrait mode
let screenWidth = bounds.width
let screenHeight = bounds.height
let aspectRatio = Float(screenHeight/screenWidth)
if(UIDevice.current.orientation.isPortrait){
mapViewC.height = mapViewC.height/aspectRatio
}
else{
mapViewC.height = mapViewC.height * aspectRatio
}
}
答
大量的研究和测试后,我发现,最可靠的方式做到这一点(据我所知)是保持全局变量,但使用的是被作为测试的手段通过了CGSize。它立即可用,而方向可能尚未设置。快速旋转或翻转设备会导致错误。在使用尺寸时,我无法触发错误,如下所示:
var previousSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if size == previousSize {return}
else{ previousSize = size}
let aspectRatio = Float(size.height/size.width)
mapViewC.height = mapViewC.height/aspectRatio
}