ios - 方向更改后如何获取屏幕高度?

标签 ios swift notificationcenter

在方向更改后查询 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/

相关文章:

ios - 打电话回来后从通知中心收到通知

iOS:有谁知道为什么我会收到 999 错误,即使页面已加载?

swift - 在 Swift 中将具有多个参数的函数作为闭包传递

ios - UIAccessibility.convertToScreenCoordinates() 总是返回一个 CGRect(0,0,0,0)

ios - 当 Accessory InputView 不存在键盘时,键盘将显示调用的通知

macos - 复制像《Mountain Lion》中的通知中心一样向一侧滑动的屏幕?

ios - Cocos2dX CCSpriteBatchNode - 无法加载 PVR 图像 Sprites.pvr.ccz

ios - 使用另一个动态 UIImage mask UIImage

javascript - 从浏览器表单提交按钮重定向到 App React Native

ios - 如何将 Temboo Http Post API 的 Objective-C 转换为 Swift iOS