简体   繁体   中英

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?

You are never creating the UIImageView .

Replace:

var homeImageView: UIImageView!

with:

let homeImageView = UIImageView()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM