简体   繁体   English

按钮添加目标 function 未在 CollectionView 单元格中调用

[英]Button add target function not called in CollectionView cell

I have a collection view where each of the cells has a delete button.我有一个集合视图,其中每个单元格都有一个删除按钮。 I added the following code to cellForItemAt indexPath function.我将以下代码添加到 cellForItemAt indexPath function。

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)

Initially it looked as if it was working great.最初它看起来好像工作得很好。 However, I found out that the add target function does not get called at the first tap if I scroll back and forth and then tap the delete button.但是,我发现如果我来回滚动然后点击删除按钮,则在第一次点击时不会调用添加目标 function。 If I tap again, it works as expected.如果我再次点击,它会按预期工作。 Only the first tap does not work.只有第一个水龙头不起作用。

I have been trying to find a reason and a solution for several hours... Please help provide any ideas and advice.几个小时以来,我一直在努力寻找原因和解决方案……请帮助提供任何想法和建议。

Try to move buttons handling into CustomCellTwo implementation.尝试将按钮处理移动到CustomCellTwo实现中。 Handle button event touchUpInside with @IBAction func .使用@IBAction func处理按钮事件touchUpInside Now you can debug it with breakpoint set in this function's body.现在您可以使用在此函数主体中设置的断点对其进行调试。 Also add closure type variable to your CustomCellTwo to pass deleteCell calls into it.还将闭包类型变量添加到您的CustomCellTwo以将deleteCell调用传递给它。 So it could also be checked with breakpoint.所以也可以用断点检查。 Example:例子:

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM