【发布时间】: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