DCDC DCDC - 1 year ago 201
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() {

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 Source

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:

UIViewController awakeFromNib
UIView awakeFromNib
UIViewController viewDidLoad

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.

layer.cornerRadius = self.frame.height / 2.0
layer.masksToBounds = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download