ios - 注册 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()
}
我做错了什么吗?我不知道为什么这仍然崩溃。
解决方案
我看到这里发生了两件事。首先,您已经注释掉了为单元格设置重用标识符的行。您需要取消注释此行:
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
}
推荐阅读
- asp.net - 配置转换,转换后无法识别的 XML 命名空间
- python - Python中的希尔伯特变换?
- c# - 如何读取 HttpWebRequest.GetResponse 引发 WebException 时返回的自定义错误消息?
- ios - 如何在点击时旋转披露指示器?
- sql - 使用子查询进行 SQL 更新
- android - 如何更改工具栏上项目的颜色
- javascript - 使用在线编辑器运行 P5.play 的问题
- docker - 为什么 Docker exec 需要 --interactive?--tty 应该够了吧?
- neo4j - 我可以使用 CSV 在 Neo4j 中导入我的主键吗
- javascript - 如何在 React 的 componentDidMount 中调用 geoLocation