无法使用全局变量访问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!

您已将单元格声明为UICollectionViewCell类型。因此,无论您将哪个子类存储在其中,您的单元格都只能是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
}
}

或者,如果你坚持在委托结束时只需要一个返回语句,那么你可以这样做,

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
}

您需要通过将cell强制转换为AttachmentCell来使编译器静音。参见以下示例,

(cell as! AttachmentCell).imgAttachment.image = imageArray1[indexPath.row]
(cell as! AttachmentCell).delegate = self

编译器无法识别变量的原因是将变量cell声明为UICollectionViewCell。由于UICollectionViewCell中并没有imgAttachment变量,所以编译器会抱怨。

最新更新