[英]swift imageView, collectionView, unexpectedly found nil while unwrapping an Optional value
First of all: I know that there are thousands of questions about this subject and for sure in one of them my question is answered. 首先:我知道关于该主题有成千上万的问题,可以肯定的是,其中一个问题得到了解答。 But after hours of searching I did not find an answer which solves my problem...
但是经过数小时的搜索,我找不到解决我问题的答案...
I have a CollectionViewController (inside a container) and a CollectionViewCell. 我有一个CollectionViewController(在容器内)和一个CollectionViewCell。 Inside the Cell there is an imageView.
单元内有一个imageView。 The image of the imageView has to be changed with a button in CollectionViewController.
必须使用CollectionViewController中的按钮更改imageView的图像。
Here is my code: 这是我的代码:
class essenCell: UICollectionViewCell {
@IBOutlet weak var Bild: UIImageView!
}
(The Cell) (细胞)
class essenCollectionViewController: UICollectionViewController {
[...]
@IBAction func xyz(sender: UIButton!) {
//following: the line with the error (unexpectedly found nil while unwrapping an Optional value)
essenCell().Bild.image = UIImage(named: "erster")
}
}
(The CollectionViewController) (CollectionViewController)
First I thought I could connect the Button to the Cell AND the Controller, this works theoretically but does not work in my specific case. 首先,我认为我可以将Button连接到Cell和Controller,这在理论上是可行的,但在我的特定情况下不起作用。 The image change happens inside an if-Loop (inside my Controller) which refers to the parentViewController.
图像更改发生在if-Loop内部(在我的控制器内部),该循环引用parentViewController。 Because I cannot use this reference inside the Cell, I need the button-function to be in the Controller.
由于无法在单元格中使用此引用,因此需要按钮功能位于控制器中。
Please help me! 请帮帮我!
All the setup for a collectionViewCell
should be done in cellForItemAtIndexPath
. collectionViewCell
所有设置都应在cellForItemAtIndexPath
完成。
var buttonPressed = false
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseCell", forIndexPath: indexPath) as! essenCell
if buttonPressed {
cell.Bild.image = UIImage(named: "erster")
} else {
cell.Bild.image = UIImage(named: "placeHolder")
return cell
}
@IBAction func xyz(sender: UIButton!) {
buttonPressed = true
collectionView?.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.