首页 > 解决方案 > 注册 collectionViewCell Xcode

问题描述

我正在尝试使用自定义 CollectionView 单元,由于某种原因,我的应用程序因错误而崩溃,

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法使类型视图出列:带有标识符 Cell 的 UICollectionElementKindCell - 必须为标识符注册一个 nib 或一个类或连接故事板中的原型单元格”

我将集合视图设置为

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! profCell
   let myColor = GREEN_Theme

    if indexPath.row == 0 {
   cell.layer.borderColor = myColor.cgColor
   cell.layer.cornerRadius = 10
   cell.layer.borderWidth = 1.0
   cell.textField.textColor = GREEN_Theme
   cell.textField.text = "Skills & Preferences"

    } else if indexPath.row == 1  {
         cell.backgroundColor = .yellow

    } else if indexPath.row == 2  {
        cell.backgroundColor = .red

    }

    return cell
}

我用

fileprivate func registerCollectionView() {
    collectionView.register(profCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: profID)
  //  collectionView.register(profCell.self, forCellWithReuseIdentifier: "profCell")
}

然后在我看来确实加载

override func viewDidLoad() {
    super.viewDidLoad()
    registerCollectionView() 
}

我做错了什么吗?我不知道为什么这仍然崩溃。

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


我看到这里发生了两件事。首先,您已经注释掉了为单元格设置重用标识符的行。您需要取消注释此行:

 collectionView.register(profCell.self, forCellWithReuseIdentifier: "profCell") 

其次,当您创建单元格时,您使用了错误的重用标识符。您需要使用“profCell”而不是“Cell”。

编辑(dahiya_boy):我以以下方式注册XIB,它也有效

如何注册 CollectionViewCell

 colView.register(UINib(nibName: "ColViewCellXib", bundle: nil), forCellWithReuseIdentifier: "ColViewCellXib")

和,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColViewCellXib", for: indexPath) as! ColViewCellXib
    return cell
}

如何注册 TableViewViewCell

 tblView.register(UINib(nibName: "TblCellXib", bundle: nil), forCellReuseIdentifier: "TblCellXib")

和,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TblCellXib") as! TblCellXib
    return cell
}

推荐阅读