【问题标题】:iOS - Wrong UIScreen bounds in viewWillTransition for iPadiOS - iPad 的 viewWillTransition 中的 UIScreen 边界错误
【发布时间】:2017-08-04 14:07:17
【问题描述】:

我必须检查我的设备是否在 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

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

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)")
    }
}

纵向>横向:false -> true

横向>纵向:true -> false

【问题讨论】:

  • viewWillTransition() 方法是在 viewDidAppear 之前还是之后调用的?

标签: ios swift ipad uiscreen viewwilltransitiontosize


【解决方案1】:

您应该尝试改用协调器上下文的 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 键。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2012-09-12
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多