ios - CoreData:如何将获取的数据显示到 UIcollectionView Cell
问题描述
目前我有这个loadCharacters函数
var characterArray = [Character]()
func loadCharacters(with request: NSFetchRequest<Character> = Character.fetchRequest()) {
do {
characterArray = try context.fetch(request)
} catch {
print("error loading data")
}
collectionView.reloadData()
}
我的问题是:如何将获取的数据从那里传递给我的子类CharacterCollectionViewCell,然后再将此单元格用于我的
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "characterCell",
for: indexPath) as! CharacterCollectionViewCell {
...
}
非常感谢任何建议或任何更好的方法来使它起作用!
解决方案
您只需要获取characterArray
对应的元素indexPath.item
并使用它来将其传递到单元格中。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "characterCell",
for: indexPath) as! CharacterCollectionViewCell {
cell.someLabel.text = characterArray[indexPath.item]
//...
return cell
}
如果要传递的数据太多,最好创建一个模型并使用它的实例将数据传递到单元格。因此,为此首先创建一个模型。
struct CharacterCellModel { // all properties... }
然后在你的UIViewController
子类中。
var characterCellModels = [CharacterCellModel]() // append this model
最后在cellForItemAt
:
cell.characterCellModel = characterCellModels[indexPath.item]
推荐阅读
- kotlin - 如何使用 Kotlin/Native 应用程序将字符串写入剪贴板(Windows 操作系统)?
- python - Django - 如何按注释值过滤
- c - c中字符数组的串联
- react-native - 任务 ':app:processDebugResources' 执行失败。> 安卓资源链接失败可以再构建RN安卓版
- ios - CoreLocation 的 requestLocation 方法的替代方案
- gcc - OpenSSL linking undefined reference to `EVP_MD_CTX_new' and others
- java - SpringExtension 没有显式配置?
- javascript - 在浏览器环境中,如何检测到所有 JavaScript 代码都已终止?
- asp.net-mvc-4 - 当页面加载动作结果在 mvc 中调用两次时
- c# - 如何从像素更改红色/绿色/蓝色/alpha 值的值