1

I am subclassing a UICollectionViewCell, this is what my code looks like

    var homeImageView : UIImageView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.configure()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configure()
    }

    func configure () {
        homeImageView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(homeImageView)

        self.setupConstraints()
    }

    func setupConstraints () {
        self.addConstraints([
            self.topAnchor.constraintEqualToAnchor(homeImageView.topAnchor),
            self.leftAnchor.constraintEqualToAnchor(homeImageView.leftAnchor),
            self.rightAnchor.constraintEqualToAnchor(homeImageView.rightAnchor),
            self.bottomAnchor.constraintEqualToAnchor(homeImageView.bottomAnchor)
            ])
    }

My app crashes and I'm getting an error message on this line

homeImageView.translatesAutoresizingMaskIntoConstraints = false

The error message

fatal error: unexpectedly found nil while unwrapping an Optional value

What is causing this? I've tried assigning an image and frame to the imageView but the app still crashes and give the same error.

In Obj-c, I would just use alloc init, set translatesAutoresizingMaskIntoConstraints to NO, add as a subview and setup its constraints and it would work. Why is this not working? What am I doing wrong?

1 Answer 1

2

You are never creating the UIImageView.

Replace:

var homeImageView: UIImageView!

with:

let homeImageView = UIImageView()
Sign up to request clarification or add additional context in comments.

1 Comment

Working now. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.