如何让UICollectionViewCell在略微超出自身的区域也能检测到点击事件
方案1:重写UICollectionViewCell的点击检测方法(推荐,改动量极小)
你不需要修改现有布局,只要自定义Cell类,重写系统的point(inside:with:)方法,手动扩大点击响应范围即可,刚好可以满足你间隙区域左右对半分配的需求:
- 自定义Cell类:
class CustomCollectionCell: UICollectionViewCell { // 替换为你实际使用的cell水平间隙值 private let horizontalSpacing: CGFloat = 4 override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // 向左右各扩展半个间隙作为响应区域,中间间隙刚好对半分给左右cell let responseArea = bounds.insetBy(dx: -horizontalSpacing/2, dy: 0) return responseArea.contains(point) } }
- 把你原来注册的Cell类替换成这个自定义类即可,原有添加手势的代码不需要任何修改,就能实现你要的效果。如果需要同时扩大上下方向的响应范围,把
dy参数也改成负值即可。
方案2:给CollectionView加全局点击手势
如果你不想给每个Cell加手势,也可以直接给整个CollectionView加全局手势,在手势回调中计算点击对应的Cell:
// 给collectionView添加全局手势 let globalTap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) collectionView.addGestureRecognizer(globalTap) // 手势回调实现 @objc private func handleTap(_ gesture: UITapGestureRecognizer) { let tapPoint = gesture.location(in: collectionView) // 水平方向偏移半个间隙,适配间隙区域的归属判断 let adjustedPoint = CGPoint(x: tapPoint.x - 2, y: tapPoint.y) // 2对应你半个间隙的数值 guard let indexPath = collectionView.indexPathForItem(at: adjustedPoint) else { return } print(indexPath.row) // 后续处理逻辑写在这里即可,原来cellForItemAt里加手势的代码可以直接删除 }
内容的提问来源于stack exchange,提问作者crost
相关产品推荐
相关产品推荐

