委托返回 nil,不是在 ViewController 中,而是在委托创建 class 中

Delegate Returning nil, not in ViewController but on Delegate creating class

在将我的问题标记为重复之前,请仔细检查我的问题, 我在我的应用程序中使用了委托模式,并且我所有与委托相关的代码都运行良好。但是现在有一个 class 在我下面描述的某个点上它的委托为 nil。

//protocol class,
protocol CampaignCollectionViewCellDelegate: class {

 func campaignCollectionViewCell(_ Cell: CampaignCollectionViewCell, didContributePressed: UIButton, at indexPath: IndexPath)

 }

 // class where delegate is assigning.

class CampaignCollectionViewCell: UICollectionViewCell {


weak var delegate: CampaignCollectionViewCellDelegate? = .none 

//here i am getting delegate as nil.
@IBAction func didContributeButtonPressed(_ sender: UIButton) {

    if self.delegate != nil {
        self.delegate?.campaignCollectionViewCell(self, didContributePressed: sender, at: self.indexPath)
        }
    }
}

在我的主要 class 中,我正在做这样的事情

@IBOutlet weak var campaignCollectionView: UICollectionView!

并在 viewDidLoad()

campaignCollectionView.delegate = self
campaignCollectionView.dataSource = self

在这里,当我调试时,我发现我的委托不是 nil,而是其中有一些对象引用,我也尝试过使用这种方式

var campaignVC = CampaignCollectionViewCell()
campaignVC.delegate = self

但这对我来说也没有用,我对所有其他委托方法都做了同样的事情,它们工作正常,我不知道为什么它会向我展示这样的行为。我已经解决了与代表相关的每一个问题,但 none 对我有用。

您在此处创建的单元格:

var campaignVC = CampaignCollectionViewCell()

与集合视图中显示的单元格不同。

您需要设置 delegate 实际显示在集合视图中的单元格,而不仅仅是任何单元格。

在您的 cellForItemAt 方法中,您可能调用了 dequeueReusableCell:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CampaignCollectionViewCell

你应该直接在上面一行之后设置委托:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CampaignCollectionViewCell
cell.delegate = self