ios - 加载 UICollectionViewCell 时,IBOutelt 发现 nil
问题描述
我正在研究如何在没有情节提要的情况下创建一个简单的应用程序,但我遇到了一个问题:我创建了一个名为 的 XIB HomeViewController
,其中有一个UICollectioView
并在viewDidLoad()
. 之后,我创建了一个名为 的单元格HomeCollectionViewCell
,将其identifier
作为“单元格”,在它有一个UILabel
插座的单元格中,它在 .swift 文件中被引用。在设置delegate
和之后datasource
,它具有数据源的强制方法,在进行单元格配置和通过设置返回 nil 的任何文本调用标签时。我不知道为什么会这样,我在 YouTube 上看过几个视频,但都没有解决问题。有谁能够帮我?
主视图控制器
class HomeViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var info = ["Image"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier:
"cell")
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection
section: Int) -> Int {
return info.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:
IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for:
indexPath) as? HomeCollectionViewCell
cell?.teste.text = "test"
return cell!
}
}
主页集合查看单元格
class HomeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var teste: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
解决方案
那是因为您必须注册单元格的笔尖而不仅仅是类:
collectionView.register(UINib(nibName: "HomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
推荐阅读
- dataframe - Pyspark 将 StrucType[ArrayType, StructureType] 转换为 ArrayType[ArrayType,ArrayType]
- javascript - HTML 足球计时器
- bash - 用bash读取csv中未定义的列数
- docker - 从 nginx-alpine 映像以非 root 身份运行 nginx 容器
- html - 创建正则表达式以仅允许小数点后的数字和 2 位数字
- java - 如何显示数组中的图像?
- node.js - webpack-dev-server v4 -window 未定义
- php - 使用自定义对象的 Twilio web-hook 实现
- python - 像浏览器一样的 Python 请求?
- android - 如何修复错误类型'String'不是'index'的'int'类型的子类型?