iOS - iPad 的 viewWillTransition 中的 UIScreen 边界错误

Mar*_*ssa 3 ipad ios uiscreen swift viewwilltransitiontosize

我必须检查我的设备是否在 iOS 8+ 中改变了方向。

我的做法是:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let isLand = UIScreen.main.bounds.width > UIScreen.main.bounds.height

    coordinator.animate(alongsideTransition: nil) { _ in
        let isLand2 = UIScreen.main.bounds.width > UIScreen.main.bounds.height


        print("\(isLand) -> \(isLand2)")
    }
}
Run Code Online (Sandbox Code Playgroud)

它在 iPhone 中运行良好,但在 iPad 中isLand已经有了新的值,应该是在定位完成后,所以:

人像 > 风景: true -> true

风景 > 人像: false -> false

根据文档,边界应该随着方向而改变,所以它应该有一个之前/之后的边界,不是吗?

UIScreen 主要边界:

这个矩形是在当前坐标空间中指定的,它考虑了对设备有效的任何界面旋转。因此,当设备在纵向和横向之间旋转时,此属性的值可能会发生变化。

如果我像这样使用当前根视图控制器的边界,它在 iPhone 和 iPad 上都可以正常工作:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let isLand = UIApplication.shared.keyWindow!.rootViewController!.view.bounds.width > UIApplication.shared.keyWindow!.rootViewController!.view.bounds.height

    coordinator.animate(alongsideTransition: nil) { _ in
        let isLand2 = UIApplication.shared.keyWindow!.rootViewController!.view.bounds.width > UIApplication.shared.keyWindow!.rootViewController!.view.bounds.height


        print("\(isLand) -> \(isLand2)")
    }
}
Run Code Online (Sandbox Code Playgroud)

人像 > 风景: false -> true

风景 > 人像: true -> false

Oli*_*son 5

您应该尝试改用协调器上下文的 containerView。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    let isLand = coordinator.containerView.bounds.width > coordinator.containerView.bounds.height

    coordinator.animate(alongsideTransition: nil) { _ in
        let isLand2 = coordinator.containerView.bounds.width > coordinator.containerView.bounds.height

        print("\(isLand) -> \(isLand2)")
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您想获得有关转换的更多信息,您可以使用func view(forKey: UITransitionContextViewKey)func viewController(forKey: UITransitionContextViewControllerKey)使用.from键。