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

iOS - Wrong UIScreen bounds in viewWillTransition for iPad

我必须检查我的设备在 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)")
    }
}

它在 iPhone 中工作正常,但在 iPad 中 isLand 已经有了应该在定向完成后的新值,所以:

纵向 > 横向:true -> true

风景 > 肖像:false -> false

根据文档,边界应该随方向改变,所以它应该有一个 before/after 边界,不是吗?

UIScreen main bounds:

This rectangle is specified in the current coordinate space, which takes into account any interface rotations in effect for the device. Therefore, the value of this property may change when the device rotates between portrait and landscape orientations.

如果我像这样使用当前根视图控制器的边界,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)")
    }
}

纵向 > 横向:false -> true

横向 > 纵向:true -> false

您应该尝试使用协调器上下文的 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)")
    }

}

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