Ios 单元格';s委托在didSelectItemAt中为零

Ios 单元格';s委托在didSelectItemAt中为零,ios,swift,uicollectionview,delegates,uicollectionviewcell,Ios,Swift,Uicollectionview,Delegates,Uicollectionviewcell,我有一个UICollectionViewCell,里面有一个桌子。桌面有一个Bool属性,我想在点击单元格时更改该属性 我试图更好地熟悉委托模式,并希望避免在单元格上使用透明按钮之类的东西。我认为在cellForItemAt中分配单元格的委托并在didSelectItemAt中触发委托方法是可行的,但当我签入didSelectItemAt时,单元格的委托为零 结构: struct Desk: Equatable, Codable { var name: String var wa

我有一个
UICollectionViewCell
,里面有一个
桌子
。桌面有一个
Bool
属性,我想在点击单元格时更改该属性

我试图更好地熟悉委托模式,并希望避免在单元格上使用透明按钮之类的东西。我认为在
cellForItemAt
中分配单元格的委托并在
didSelectItemAt
中触发委托方法是可行的,但当我签入
didSelectItemAt
时,单元格的委托为零

结构:

struct Desk: Equatable, Codable {
    var name: String
    var wasTouched: Bool = false
}
协议:

protocol TouchTheDesk: AnyObject {
    func youTouchedIt(cell: DeskCell)
}
单元格:

使VC符合协议并定义委托方法:

extension NotAShoppingListVC: TouchTheDesk {
    func youTouchedIt(cell: DeskCell) {
        if cell.desk?.wasTouched != nil {
            cell.desk!.wasTouched = !cell.desk!.wasTouched
        } else {
            cell.desk!.wasTouched = true
        }
        collectionView.reloadData()
    }
}
cellForItemAt:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return UICollectionViewCell()}
    cell.desk = deskDealer.desks[indexPath.item]
    if cell.desk!.wasTouched { //assigned on line above
        cell.backgroundColor = .red
    } else {
        cell.backgroundColor = .green
    }
    cell.delegate = self
    return cell
}
didSelectItemAt:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return}
    #warning("delegate is nil")
    cell.delegate?.youTouchedIt(cell: cell)
}

编辑:如果我在
didSelectItemAt
中直接调用委托方法并传入单元格,则在
didSelectItemAt
Replace中,委托方法中单元格的indexPath为nil

 guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return}


当您在
cellForItemAt
之外使用
dequeueReusableCell
时,它将返回一个与单击的单元格不同的单元格

您不允许在
cellForItemAt
之外调用
dequeueReusableCell
。您是说您在didSelectItemAt方法中得到了indexath nil吗?谢谢,我显然需要阅读可重用视图,而不是委托模式lol
 guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return}
guard let cell = collectionView.cellForItem(at: indexPath) as? DeskCell else {return}