繁体   English   中英

Swift-以编程方式创建UIImageView时应用崩溃

[英]Swift - App crahes when create UIImageView programmatically

我在子类化UICollectionViewCell,这就是我的代码

    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)
            ])
    }

我的应用程序崩溃,并且在此行上收到一条错误消息

homeImageView.translatesAutoresizingMaskIntoConstraints = false

错误讯息

致命错误:解开Optional值时意外发现nil

是什么原因造成的? 我尝试将图像和框架分配给imageView,但该应用程序仍然崩溃并给出相同的错误。

在Obj-c中,我只使用alloc init,将translatesAutoresizingMaskIntoConstraints设置为NO,添加为子视图并设置其约束即可。 为什么这不起作用? 我究竟做错了什么?

您永远不会创建UIImageView

更换:

var homeImageView: UIImageView!

有:

let homeImageView = UIImageView()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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