gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:19:58 26 4
gpt4 key购买 nike

我正在对 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

错误信息

fatal error: unexpectedly found nil while unwrapping an Optional value

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

在 Obj-c 中,我只使用 alloc init,将 translatesAutoresizingMaskIntoConstraints 设置为 NO,添加为 subview 并设置其约束,它就可以工作了。为什么这不起作用?我做错了什么?

最佳答案

您永远不会创建 UIImageView

替换:

var homeImageView: UIImageView!

与:

let homeImageView = UIImageView()

关于ios - Swift - 以编程方式创建 UIImageView 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39679394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com