为 UICollectionViewCell 的一部分阻止 `didSelect…`

Prevent `didSelect…` for part of a UICollectionViewCell

总结

UICollectionViewCell 子类是否可以阻止 didSelectItemAt: indexPath 被发送到 UICollectionViewDelegate 以便点击 它的某些子视图 ,但要继续对其他人来说正常吗?

用例

我有一个 UICollectionViewCell 表示一篇文章的摘要。对于大多数文章,当它们被点击时,我们会浏览以显示文章。

但是,某些文章摘要会显示内联视频预览。当点击视频预览时,我们不应该浏览,但是当点击文章摘要的其他区域(标题)时,我们应该浏览。

我希望文章摘要单元格能够决定点击它是否应被视为选择。

  1. You have to add tapGestureRecogniser on those subviews of cell on which you don't want delegate to get called.

  2. tapGestureRecogniser selector method will get called when you will tap on those subview and gesture will not get passed to delegate.

您需要做的是将 UITapGestureRecognizer 附加到您的视图并监控来自它的点击:

class MyViewController: UIViewController, UICollectionViewDataSource, MyCellDelegate {

    var dataSource: [Article] = []

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ArticleCell", for: indexPath) as! MyCell
        cell.article = dataSource[indexPath.row]
        cell.delegate = self
        return cell
    }

    func articleDidTap(_ article: Article) {
        // do what you need
    }

}



// your data model
struct Article {}


protocol MyCellDelegate: class {
    func articleDidTap(_ article: Article)
}


class MyCell: UICollectionViewCell {

    var article: Article! {
        didSet {
            // update your views here
        }
    }
    weak var delegate: MyCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MyCell.tap)))
    }

    @objc func tap() {
        delegate?.articleDidTap(article)
    }

}

这应该有效,因为您的视频视图应该与根视图重叠并防止接收来自手势识别器的点击。