如何在方向更改后获取屏幕高度?
在定位更改后查询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
正确的方法来监测方向变化?
你应该使用的是 viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
。这会给你的大小,并且比使用通知更可靠。
另外,如果你想要做的动画,在UIViewControllerTransitionCoordinator里面,你可以利用该方法animate(alongsideTransition animation: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)?, completion: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)? = nil) -> Bool
我已经试过这个,它的行为与我的问题中的代码完全相反。即。它会报告iPad上的正确尺寸,但iPhone上的尺寸错误。 – Turnip
您是否尝试过使用动画(alongsideTransition ...)?我已经使用了这个方法,并且在完成这个方法时,一切似乎都落空了。 –
所以当我创建一个测试项目并打印出iPhone的大小时,我得到:'landscape(736.0,414.0)'和'portrait(414.0,736.0)',然后对于iPad我得到'landscape(1024.0,768.0)'和'肖像(768.0,1024.0)'。这些是iPad Air 2和iPhone 8. –
这雨燕2.3对我的作品都为iPad和iPhone。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
print(size.height)
if UIDevice.currentDevice().orientation.isLandscape {
print("Landscape")
print(size.height)
}
else {
print("Portrait")
print(size.height)
}
}
您是否将'screenHeight'值变大或变小? – Srdjan
停止使用screensize = UIScreen.main.bounds并改为使用大小,它会在方法中提供给您。你可以做size.height * 0.75 –
另外,如果你正在使用约束条件,并且你的searchView等于你的视图的高度,那么在同一个heighViewConstraint上,你可以将修饰符设置为0.75,如果它总是会达到那个尺寸。然后,你将得到的旋转视图将更新自己,你根本不必做任何逻辑。 –