DCDC DCDC - 2 months ago 69
iOS Question

Swift 3: Wrong UIView size read

I have an UIView that is set to be 50x50 sized in interface builder.

After the view is loaded in the app, it looks perfectly fine, but when I print its size after it get's loaded

override func awakeFromNib() {
print(self.frame.height)
}


it returns 1000.0

This error has not occurred until I updated my project to Swift 3.0

Anybody got any idea what might have changed? Why printing it's height return 1000.0 while it's actually 50.0?

Answer

This is because the UIView has not set to 50x50 at that point in life circle. At this point it's 1000.0 - a standard size.

The circle is:

init    
UIViewController awakeFromNib
loadView
UIView awakeFromNib
UIViewController viewDidLoad
viewWillAppear
viewDidAppear

From then on properties like the size are available to work with.

You need to use the layoutIfNeeded property to have access to the layout early.

self.layoutIfNeeded()
layer.cornerRadius = self.frame.height / 2.0
layer.masksToBounds = true
Comments