0

我有一个集合视图,其中每个单元格都有一个删除按钮。我将以下代码添加到 cellForItemAt indexPath 函数。

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

cell.deleteButton.layer.setValue(indexPath.row, forKey: "index")

cell.deleteButton.addTarget(self, action: #selector(deleteCell), for: .touchUpInside)

最初它看起来好像工作得很好。但是,我发现如果我来回滚动然后点击删除按钮,则在第一次点击时不会调用添加目标函数。如果我再次点击,它会按预期工作。只有第一个水龙头不起作用。

几个小时以来,我一直在努力寻找原因和解决方案……请帮助提供任何想法和建议。

4

1 回答 1

0

尝试将按钮处理移动到CustomCellTwo实现中。touchUpInside用处理按钮事件@IBAction func。现在您可以使用在此函数主体中设置的断点对其进行调试。还要向您添加闭包类型变量以将调用CustomCellTwo传递给它。deleteCell所以也可以用断点检查。例子:

class CustomCellTwo: UICollectionViewCell {
    var onDelete: (() -> Void)?
    @IBAction func onDeleteButtonTouch(_ sender: Any) {
        onDelete?()
    }
}


// in your UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo
    cell.onDelete = {
        self.deleteCell(indexPath)
    }
}
于 2020-06-22T11:23:38.387 回答