首页 > 解决方案 > UICollectionViewCell 委托不会触发

问题描述

我显然做错了什么,但还不能确定在哪里。我将单元格设置如下:

protocol PropertyPhotoCellDelegate: class {
    func deletePropertyPhoto(cell: PropertyPhotoCell)
}

class PropertyPhotoCell: UICollectionViewCell {

    weak var propertyPhotoCellDelegate: PropertyPhotoCellDelegate?

    let deleteButton: UIButton = {
        let button = UIButton()
        let image = UIImage(named: "delete.png")
        button.setImage(image, for: .normal)
        button.showsTouchWhenHighlighted = true
        button.isHidden = true
        button.addTarget(self, action: #selector(handleDeleteButton), for: .touchUpInside)
        return button
    }()

        var isEditing: Bool = false {
        didSet {
            deleteButton.isHidden = !isEditing
        }

    }

我省略了设置单元格视图。这是选择器

@objc fileprivate func handleDeleteButton() {
    propertyPhotoCellDelegate?.deletePropertyPhoto(cell: self)

}

在 UICollectionViewController 中,我分配了委托

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
        cell.photoImageView.image = photos[indexPath.item]
        cell.propertyPhotoCellDelegate = self

        return cell
 }

这将隐藏或显示单元格上所有视图中的单元格的删除按钮

override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    navigationItem.rightBarButtonItem?.isEnabled = !editing

    if let indexPaths = collectionView?.indexPathsForVisibleItems {
        for indexPath in indexPaths {
            if let cell = collectionView?.cellForItem(at: indexPath) as? PropertyPhotoCell {
                cell.deleteButton.isHidden = !isEditing
            }
        }
    }
}

最后,符合这里的协议

extension PropertyPhotosController: PropertyPhotoCellDelegate {

    func deletePropertyPhoto(cell: PropertyPhotoCell) {

        if let indexPath = collectionView?.indexPath(for: cell) {
            photos.remove(at: indexPath.item)
            collectionView?.deleteItems(at: [indexPath])
        }
    }
}

我点击UICollectionViewController Edit按钮,所有单元格都按预期显示删除按钮。任何单元格的delete按钮都会在点击时突出显示,但我没有看到delegate被调用。

标签: swiftdelegatesuicollectionviewcell

解决方案


在 UICollectionViewController 中分配委托时,还要为单元格设置选择器。

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! PropertyPhotoCell
    cell.photoImageView.image = photos[indexPath.item]
    cell.propertyPhotoCellDelegate = self
    cell.deleteButton.addTarget(cell, action: #selector(cell.handleDeleteButton), for: .touchUpInside)
    cell.deleteButton.isHidden = true
    return cell
}

推荐阅读