【问题标题】:swift imageView, collectionView, unexpectedly found nil while unwrapping an Optional valueswift imageView,collectionView,在展开可选值时意外发现nil
【发布时间】:2015-11-26 17:47:44
【问题描述】:

首先:我知道关于这个主题有成千上万个问题,并且肯定在其中一个问题中我的问题得到了解答。但经过数小时的搜索,我没有找到解决我问题的答案......

我有一个 CollectionViewController(在容器内)和一个 CollectionViewCell。在 Cell 里面有一个 imageView。必须使用 CollectionViewController 中的按钮更改 imageView 的图像。

这是我的代码:

class essenCell: UICollectionViewCell {
@IBOutlet weak var Bild: UIImageView!
}

(细胞)

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

(集合视图控制器)

首先我认为我可以将按钮连接到单元和控制器,这在理论上可行,但在我的特定情况下不起作用。 图像更改发生在指向 parentViewController 的 if-Loop 内(在我的 Controller 内)。因为我不能在 Cell 中使用这个引用,所以我需要在 Controller 中使用按钮功能。

帮帮我!

【问题讨论】:

    标签: ios swift null


    【解决方案1】:

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

    【讨论】:

    • 这真的很好,谢谢。但是有什么方法可以使用parentViewController 中的"reloadData()" 部分吗?我已经尝试过essenViewController().collectionView?.reloadData(),但这不起作用。我收到错误“uicollectionview 必须使用非零布局参数 swift 初始化”
    • 使用NSNotificationCenter 通知向collectionViewController 发送信号。这是在 VC IMO 之间发送信号的最简单方法。
    猜你喜欢
    • 2018-09-22
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多