我正在使用自定义UICollectionViewCell,在UICollectionView中将其称为ExampleCell,而我尝试为单元格设置的图像未显示,并且应用程序崩溃。我发现了一个类似的问题here,据我所知,我一直遵循这些评论,但这没有帮助。

当我注释掉

self.collectionView!.registerClass(RedeemCell.self, forCellWithReuseIdentifier: reuseIdentifier)


在ExampleCollectionViewController内部,该应用程序不会崩溃,而是显示黑框(因为我将单元格背景色设置为黑色),而不是实际图像。如果我取消注释该行,则应用程序因错误而崩溃

fatal error: unexpectedly found nil while unwrapping an Optional value


ExampleCollectionViewController.swift:

import UIKit

private let reuseIdentifier = "ExampleCell"
private let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)

class ExampleCollectionViewController: UICollectionViewController {
    let examples = Example.allExamples()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(ExampleCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return examples.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> ExampleCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ExampleCell
        cell.backgroundColor = UIColor.blackColor()
        cell.configureForExample(examples[indexPath.row])
        return cell
    }
}


ExampleCell.swift:

import UIKit

class ExampleCell: UICollectionViewCell {
    @IBOutlet weak var exampleImageView: UIImageView!

    func configureForExample(example: Example) {
        exampleImageView.image = example.image
    }
}


Example.swift

import UIKit

@objc
class Example {
    let image: UIImage?

    init(image: UIImage?) {
        self.image = image
    }

    class func allExamples() -> Array<Example> {
        return [Example(image: UIImage(named: "Neutral")),
            Example(image: UIImage(named: "Sad")),
            Example(image: UIImage(named: "Happy")) ]
    }
}


在Identity Inspector中,我为ExampleCollectionViewController和ExampleCell设置了自定义类。另外,在属性检查器中,我将“ ExampleCell”设置为ExampleCell的“集合可重用视图”下的标识符。

关于我可能做错了什么的任何想法?

最佳答案

显然,如果我设置了背景色,然后尝试设置图像,

        cell.backgroundColor = UIColor.blackColor()
        cell.configureForExample(examples[indexPath.row])


黑色会显示在图像上方。当我摆脱黑色背景色的线条时,出现了我的图像。想想我花了几个小时,大声笑。

10-07 19:50