方向改变后如何获得屏幕高度?

问题描述 投票:1回答:3

在定向更改后查询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监控方向变化的正确方法?

ios swift notificationcenter
3个回答
3
投票

你应该使用的是viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)。这将为您提供尺寸,并且比使用通知更可靠。

此外,如果你想做动画,在UIViewControllerTransitionCoordinator内你可以利用方法animate(alongsideTransition animation: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)?, completion: ((UIViewControllerTransitionCoordinatorContext) -> Swift.Void)? = nil) -> Bool


1
投票

你需要使用:

dispatch_async(dispatch_get_main_queue()) { 
println("h:\(view.bounds.size.height)")
println("w:\(view.frame.size.width)")
         }

//你需要在dispatch_async下编写代码

旋转完成后(在主队列中)将执行此代码,并且新的大小可用。


0
投票

对于iPad和iPhone,这适用于Swift 2.3。

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)
     }

}
© www.soinside.com 2019 - 2024. All rights reserved.