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

Geo*_*gey 5 rotation ios swift

有一个视图,我在故事板中添加约束,所以它会在屏幕旋转后改变它的大小,那么如何在屏幕旋转后获得它的高度和宽度?我在这样的旋转事件函数中尝试了这个:

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

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

"现在是风景,高度是......宽度是......""现在是肖像,高度是...宽度是..."在旋转事件功能

cro*_*m87 14

您正在使用的功能说"将转换",这意味着转换未完成,因此您无法获取新的大小.

你需要使用:

dispatch_async(dispatch_get_main_queue()) { 
    println("h:\(view.bounds.size.height)")
    println("w:\(view.frame.size.width)")
             }
Run Code Online (Sandbox Code Playgroud)

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

问候.


小智 6

斯威夫特3

针对Swift 3更新了crom87的答案:

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)" )
  }
}
Run Code Online (Sandbox Code Playgroud)