>我正在尝试使用自定义的 CollectionView 单元格,但由于某种原因,我的应用程序崩溃并出现错误,
由于未捕获的异常"NSInternalInconsistencyException"而终止应用,原因:"无法将具有标识符单元格的视图取消排队:UICollectionElementKindCell 具有标识符 Cell - 必须为标识符注册 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()
}
难道我做错了什么?我不确定为什么这仍然崩溃。
我看到这里发生了两件事。首先,您注释掉了为单元格设置重用标识符的行。您需要取消注释此行:
collectionView.register(profCell.self, forCellWithReuseIdentifier: "profCell")
其次,当您创建单元格时,您使用了错误的重用标识符。您需要使用"profCell"而不是"Cell"。
编辑(dahiya_boy(:我以以下方式注册XIB,它也是有效的
如何注册收藏视图单元格
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
}
如何注册表视图视图单元格
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
}