imstillalive imstillalive - 2 months ago 19
Swift Question

Swift - App crahes when create UIImageView programmatically

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?

Answer

You are never creating the UIImageView.

Replace:

var homeImageView: UIImageView!

with:

let homeImageView = UIImageView()
Comments