比在 func 之外使用 var 跟踪设备方向更好的方法?

Better way than using a var outside a func to track device orientation?

注意:此处寻求的非特定解决方案是如何在屏幕尺寸未更改的情况下避免触发代码,例如在 Y 轴上翻转 iPad(从 landscapeLeft 到 landscapeRight)以在不调整大小的情况下向某人显示视图。换句话说,视图将在不调整任何大小的情况下旋转)。该测试基本上验证没有发生向不同方向的中间旋转。

我正在开发一款地图应用,希望在方向之间切换时保持缩放级别不变。但是,当不支持人像颠倒时,出现了一个错误,这是我想要使用手机的方式,而不是 iPads(没有任何问题)。

当我在纵向和横向之间来回旋转设备时,没有问题。但是从横向模式旋转到纵向颠倒不会触发 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
    }
}

经过大量研究和测试,我发现最可靠的方法(AFAIK)是保留全局变量,但使用正在传递的 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
}