【问题标题】:How can I get the height of a view after screen rotation in swift?如何在快速屏幕旋转后获得视图的高度?
【发布时间】:2015-03-24 13:32:54
【问题描述】:

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

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

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

"现在是横向,高度是...宽度是..." “现在是纵向,高度是......宽度是......” 在旋转事件函数中

【问题讨论】:

  • 我打印了size.height和size.width,我认为结果是设备的大小,而不是我的某些看法

标签: ios swift rotation


【解决方案1】:

你正在使用的函数说“Will tr​​ansition”,这意味着过渡没有完成,所以你无法获取新的大小。

你需要使用:

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

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

问候。

【讨论】:

  • 我对 swift 很陌生,我不确定我是否做得对,但似乎我得到了我想要的。你的意思是把 dispatch_async 放在 viewWillTransitionToSize() 中吗?我试过这样,它奏效了。谢谢。
  • 是的,你必须把它放在那里。您应该阅读一些有关 iOS 中 GDC 的教程,您将需要。基本上,当执行所有先前的功能/任务时,将执行该代码,在您的情况下,当进行轮换时。
  • 太棒了...@crom87 我犯了一个错误,但根据你的回答,我猜对了
【解决方案2】:

斯威夫特 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)" )
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多