如何在 swift 屏幕旋转后获取视图的高度?

How can I get the height of a view after screen rotation in swift?

有一个view,我在storyboard中添加了constraints,让它在屏幕旋转后改变尺寸,那么如何获取屏幕旋转后的高度和宽度呢?我在这样的旋转事件函数中试过这个:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) 
{
    println("h:\(view.bounds.size.height)")
    println("w:\(view.frame.size.width)")
}

但它只给我旋转发生前的尺寸。我想得到类似的东西:

"now is landscape, height is...width is..." "now is portrait, height is ...width is..." 在旋转事件函数中

您使用的函数显示"Will transition",这意味着转换尚未完成,因此您无法获取新尺寸。

您需要使用:

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

此代码将在轮换完成(在主队列中)并且新尺寸可用后执行。

此致。

Swift 3

crom87 答案已更新 Swift 3:

override func viewWillTransition( to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator ) {
  DispatchQueue.main.async() {
    print( "h:\(self.view.bounds.size.height)" )
    print( "w:\(self.view.frame.size.width)" )
  }
}