在方向更改后查询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处于横向方向,则UIScreen.main.bounds.height
将返回与纵向方向中的高度相同的值,反之亦然。
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
方法来监测屏幕方向的变化,但是这个方法与上面的方法完全相反。例如,在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
监测方向变化是否正确?
screenHeight
值是更大还是更小? - Srdjan