加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:38:59 所属栏目:百科 来源:网络整理
导读:在这里,我创建了一个collectionView单元变量来访问这两个对象.但是无法访问单元格变量中的对象 func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) - UICollectionViewCell { var cell: UICollectionViewCell! if
在这里,我创建了一个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
    }
}

或者,如果你是坚定的,你只需要在委托结束时只有一个return语句,那么你可以这样做,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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读