swift - 无法使用全局变量访问 collectionView 单元格变量
问题描述
在这里,我创建了一个用于访问这两个对象的 collectionView 单元格变量。但无法访问单元格变量中的对象
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell!
if collectionView == collectionView1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachment", for: indexPath) as! AttachmentCell
cell.imgAttachment.image = imageArray1[indexPath.row]
cell.delegate = self
}
else if collectionView == collectionView2 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachmentView", for: indexPath) as! AttachmentViewCell
cell.imgFileIcon.image = imgArray2[indexPath.row].fileIcon
}
return cell
'UICollectionViewCell?' 类型的值 没有成员“imgAttachment”
解决方案
问题就在这里。
var cell: UICollectionViewCell!
您已将单元格声明为 type UICollectionViewCell
。因此,无论您在其中存储哪个子类,您的单元格都只会是 type UICollectionViewCell
。
你应该这样改
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView === collectionView1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachment", for: indexPath) as! AttachmentCell
cell.imgAttachment.image = imageArray1[indexPath.row]
cell.delegate = self
return cell
} else if collectionView === collectionView2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachmentView", for: indexPath) as! AttachmentViewCell
cell.imgFileIcon.image = imgArray2[indexPath.row].fileIcon
return cell
} else {
// Return the proper cell for other cases
}
}
或者,如果您坚持在委托的末尾只需要一个 return 语句,那么您可以这样做,
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var yourCell: UICollectionViewCell!
if collectionView === collectionView1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachment", for: indexPath) as! AttachmentCell
cell.imgAttachment.image = imageArray1[indexPath.row]
cell.delegate = self
yourCell = cell
} else if collectionView === collectionView2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAttachmentView", for: indexPath) as! AttachmentViewCell
cell.imgFileIcon.image = imgArray2[indexPath.row].fileIcon
yourCell = cell
} else {
// Return the proper cell for other cases
}
return yourCell
}
推荐阅读
- groovy - 在 jmeter 后处理器中设置变量并在非 GUI 模式下在命令提示符下访问
- xml - 为什么我不能对节点名称使用 XPath 表达式
- python - 基于 Pandas DataFrame 更新 SQL Server 中某些表列的最佳方法?
- python - Pandas,根据范围创建列
- python - 对象检测交叉验证
- c# - 证书保存请求没有 DNS 的 WCF Web 服务
- node.js - Puppeteer 类型 node_modules/puppeteer/lib/types"' 没有导出成员 'Cookie'
- roomle - Rails 6 中的 Roomle SDK,使用 webpacker,抛出错误
- css - 如何通过包含字体路径的 source() 在模板中加载 CSS 文件
- javascript - Dynamodb:使用地图索引更新地图数组