在方向更改后查询 UIScreen.main.bounds.height
时,我得到了一些奇怪的结果。也许这不是正确的方法。
我有一个监听 NSNotification.Name.UIDeviceOrientationDidChange
事件的观察者:
NotificationCenter.default.addObserver(self, selector: #selector(self.orientationChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
这会调用一个函数,将约束设置为新屏幕高度的 75%。这在 iPhone 上工作正常,但 iPad 返回错误的屏幕高度。
如果 iPad 处于landscape 方向 UIScreen.main.bounds.height
将返回一个等于 portrait 方向高度的值,并且反之亦然。
func orientationChange() {
// This will print the correct value on iPhone and iPad.
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
let screenSize = UIScreen.main.bounds
let screenHeight = screenSize.height
self.searchViewHeightConstraint.constant = screenHeight * 0.75
// Correct value on iPhone. Incorrect on iPad.
print("screenHeight: '\(screenHeight)'")
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.searchView.superview?.layoutIfNeeded()
}, completion: nil)
}
我也遇到过监视方向变化的 viewWilltransition
方法,但它的行为方式与上述方法完全相反。 IE。高度在 iPad 上正确,但在 iPhone 上不正确:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let screenSize = UIScreen.main.bounds
let screenHeight = screenSize.height
self.searchViewHeightConstraint.constant = screenHeight * 0.75
// Correct value on iPad. Incorrect on iPhone.
print("screenHeight: '\(screenHeight)'")
}
iPhone 和 iPad 之间这种不一致行为的原因是什么?使用 NotificationCenter
是监控方向变化的正确方法吗?
最佳答案
你应该使用的是
viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
.这将为您提供尺寸,并且比使用通知更可靠。
另外,如果你想做动画,在 UIViewControllerTransitionCoordinator 中你可以利用方法 animate(alongsideTransition animation: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)?, completion: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)? = nil) -> Bool
关于ios - 方向更改后如何获取屏幕高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649186/