Bartosz Woźniak Bartosz Woźniak - 1 year ago 134
Swift Question

UIScreen.main.bounds.width returning nil in Swift 3

In my project, I got messed up with two versions of app. I propably copied the project file and it created a problem. This line

myLogo.frame.size.width = UIScreen.main.bounds.width


shows, that
UIScreen.main.bounds.width
returns nil. How is that even possible?


fatal error: unexpectedly found nil while unwrapping an Optional value


What could be the reason and how can I repair it?

I'm working on the latest Xcode and writing in Swift 3.

Answer Source

Be sure myLogo is connected to your storyboard (the little dot to the left of myLogo's declaration should be dark). Then set it's frame's width property like this:

    let width = UIScreen.main.bounds.width
    let r = myLogo.frame
    myLogo.frame = CGRect(x: r.origin.x, y: r.origin.y, width: width, height: r.height)

This would probably be better to do in Interface Builder with auto-layout so myLogo's width is constrained to the device's width.

Here's a useful extension that lets you adjust individual properties of a UIView's frame e.g.

myLogo.width = UIScreen.main.bounds.width
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download