gpt4 book ai didi

swift - 无法使用全局变量访问 collectionView 单元格变量

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:15 25 4
gpt4 key购买 nike

在这里,我创建了一个 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

Value of type 'UICollectionViewCell?' has no member '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
}
}

或者,如果您坚持在委托(delegate)的末尾只需要一个返回语句,那么您可以这样做,

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
}

关于swift - 无法使用全局变量访问 collectionView 单元格变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53476434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com