gpt4 book ai didi

ios - 自定义 UICollectionViewCell 不显示 UIImage 和崩溃

转载 作者:行者123 更新时间:2023-11-29 01:51:57 28 4
gpt4 key购买 nike

我在 UICollectionView 中使用自定义的 UICollectionViewCell,我称之为 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
}
}

示例.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")) ]
}
}

在身份检查器中,我为 ExampleCollectionViewController 和 ExampleCell 设置了自定义类。此外,在属性检查器中,我将“ExampleCell”设置为 ExampleCell 的“Collection Reusable View”下的标识符。

关于我可能做错了什么有什么想法吗?

最佳答案

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

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

图像上出现黑色。当我去掉黑色背景色的线条时,我的图像就出现了。想想我在这上面花了几个小时,哈哈。

关于ios - 自定义 UICollectionViewCell 不显示 UIImage 和崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31304935/

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