【问题标题】:Swift 3 UICollectionView ErrorSwift 3 UICollectionView 错误
【发布时间】:2017-06-18 16:43:37
【问题描述】:

在我的 iOS 应用程序中,我有一个 UICollectionView 控制器,其中包含以下代码:

var images = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()

    loadImages()
    // Register cell classes
}

func loadImages() {
    images.append(UIImage(named: "ActivityTab")!)
    self.collectionView?.reloadData()
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return images.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EventCollectionViewCell

    let image = images[indexPath.row]

    cell.imageView.image = image

    return cell
}

我有一个 UICollectionViewCell (EventCollectionViewCell),代码如下:

@IBOutlet weak var imageView: UIImageView!

override func prepareForReuse() {
    super.prepareForReuse()
    self.imageView.image = nil
}

我也将所有内容与故事板联系起来。这看起来应该可以工作,但我收到以下错误:

无法将 'UICollectionViewCell' (0x1092c04a8) 类型的值转换为 EventCollectionViewCell'

有谁知道错误是什么以及如何解决它。它只在我返回 images.count 时显示。

我正在使用 xcode 9,但已尝试使用 xcode 8,但错误仍然存​​在。任何帮助将不胜感激。 :)

【问题讨论】:

  • loadImages(){ is // Register cell classes} 你在那里正确注册了EventCollectionViewCell 吗?

标签: swift xcode uicollectionview uicollectionviewcell


【解决方案1】:

让我们改变这行代码:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! EventCollectionViewCell

到:

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? EventCollectionViewCell else { return UICollectionViewCell() }

【讨论】:

  • 我试过这个但得到了一个不同的错误:从 -collectionView:cellForItemAtIndexPath: 返回的单元格没有重用标识符 - 单元格必须通过调用 -dequeueReusableCellWithReuseIdentifier:forIndexPath:' 检索>
  • 我需要看你的代码来注册单元类,完整的代码是什么?
  • 导入 UIKit 类 EventCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView!覆盖 func prepareForReuse() { super.prepareForReuse() self.imageView.image = nil } }
【解决方案2】:

检查以下内容:

  1. EventCollectionViewCell 是 UICollectionViewCell 的子类。
  2. 您是否在collectionView 注册了EventCollectionViewCell?
  3. EventCollectionViewCell 与您在使用“reuseIdentifier”调用 dequeueReusableCell 时使用的 Reusable Identifier 相同。

这里reuseIdentifier的值是多少?

【讨论】:

  • 我已经检查了所有这些东西,reuseidentifier 的值是“单元格”,这也是故事板上我的单元格中的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2017-06-22
  • 1970-01-01
相关资源
最近更新 更多