tryingtolearn
tryingtolearn

Reputation: 2636

Issue with setting image UILabel swift - found nil while unwrapping optional

Code currently looks like this:

    lazy var placeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor(patternImage: UIImage(named: "placelabel")!)
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }()

I'm not sure why but when I input label.backgroundColor() the program can't run and breaks on that line.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

When I remove it and continue with my setup it seems to run fine. I've seen other comments on issues like this saying that the view isn't setup when the command is called but I'm pretty much doing the exact same thing with my buttons and whatnot and it's all working fine.

Any idea why this is happening?

Thanks

Upvotes: 0

Views: 213

Answers (2)

JohnMorrison
JohnMorrison

Reputation: 504

make sure you are using the correct asset name and spelling, and that the file actually exists on disk where its expected to be.

Upvotes: 0

Zach Lucas
Zach Lucas

Reputation: 1641

In this line, UIColor(patternImage: UIImage(named: "placelabel")!), you are forcing the unwrapping of the UIImage object using the !. If no image named "placelabel" exists in your project, the app will crash, as you are trying to unwrap nil.

Upvotes: 1

Related Questions