UIButton.frame.origin.y 不是正确的值

UIButton.frame.origin.y is not the correct value

我有一个按钮,它有一个 bottom-space-to-Superview 约束,常量为 0,将它放在屏幕的底部。从视觉上看,当我 运行 应用程序时,这正是正在发生的事情——按钮位于屏幕底部。在代码中,我想获取按钮的 frame.origin.y 以便我可以通过编程方式将其他对象放置在按钮上方。

frame.origin.y + frame.height 应该等于屏幕的高度,因为它紧靠底部放置,但我从检查 UIButton 的框架中得到的值不正确.

使用 println 查看值:

println("HomeBtn starts: \(homeBtn.frame.origin.y)")
println("HomeBtn height: \(homeBtn.frame.height)")
println("Screen height: \(self.view.frame.height)")

这是结果...

在 iPhone 6+:

HomeBtn starts: 528.0
HomeBtn height: 72.0
Screen height: 736.0

在 iPhone 5:

HomeBtn starts: 528.0
HomeBtn height: 72.0
Screen height: 568.0

iPad:

HomeBtn starts: 528.0
HomeBtn height: 72.0
Screen height: 1024.0

528 和 72 对应于 Storyboard/Interface Builder 中为 HomeBtn 显示的值,但是对于自动布局和不同的设备尺寸,这些值应该因设备而异。

有没有更好的解决方案来获取 UIView 的位置(无论是 button/imageView/label/etc)在自动布局放置之后而不是使用它的 frame.origin 和 frame.height/width 值?

Auto Layout 运行之前,不会设置子视图的框架信息。您第一次有机会看到子视图的布局是在 viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    // Now that the views are all laid out, we can check their positions.
    println("HomeBtn starts: \(homeBtn.frame.origin.y)")
    println("HomeBtn height: \(homeBtn.frame.height)")
    println("Screen height: \(self.view.frame.height)") 
}