[英]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.