[英]Swift - App crahes when create UIImageView programmatically
I am subclassing a UICollectionViewCell, this is what my code looks like 我在子类化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)
])
}
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
致命错误:解开Optional值时意外发现nil
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.
我尝试将图像和框架分配给imageView,但该应用程序仍然崩溃并给出相同的错误。
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. 在Obj-c中,我只使用alloc init,将translatesAutoresizingMaskIntoConstraints设置为NO,添加为子视图并设置其约束即可。 Why is this not working?
为什么这不起作用? What am I doing wrong?
我究竟做错了什么?
You are never creating the UIImageView
. 您永远不会创建
UIImageView
。
Replace: 更换:
var homeImageView: UIImageView!
with: 有:
let homeImageView = UIImageView()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.