You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重写UICollectionViewCell的touchesBegan后didSelectItemAt失效,需实现点击动画

解决UICollectionViewCell重写touches方法后didSelectItemAt代理失效问题

当你在自定义UICollectionViewCell中重写touchesBegan、touchesEnded等触摸方法但未调用父类对应方法时,触摸事件会被Cell拦截,无法向上传递给UICollectionView,导致ViewController中的didSelectItemAt代理方法无法触发。以下是两种可行的解决方案:

方案一:在Cell的触摸方法中调用父类实现

只需在每个重写的touches方法开头添加super调用,保证事件能正常传递到UICollectionView:

public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event) // 关键:让事件继续向上传递
    UIView.animate(withDuration: 0.5) {
        self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
    }
}

public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    UIView.animate(withDuration: 0.1) {
        self.transform = CGAffineTransform(scaleX: 1, y: 1)
    }
}

public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
    UIView.animate(withDuration: 0.1) {
        self.transform = CGAffineTransform(scaleX: 1, y: 1)
    }
}

方案二:利用UICollectionView代理方法实现动画(推荐)

这种方式无需重写Cell的触摸方法,完全依托UICollectionView的代理逻辑处理选中事件和动画,代码结构更符合iOS开发规范:

1. 给CustomCell添加统一动画方法

class CustomCellClass: UICollectionViewCell {
    // 统一处理选中/取消选中的动画
    func updateSelectionAnimation(isSelected: Bool) {
        let targetScale: CGFloat = isSelected ? 0.9 : 1.0
        let animationDuration: TimeInterval = isSelected ? 0.5 : 0.1
        
        UIView.animate(withDuration: animationDuration) {
            self.transform = CGAffineTransform(scaleX: targetScale, y: targetScale)
        }
    }
}

2. 在ViewController代理中触发动画

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
    selectedIndex = indexPath.item
    
    // 触发选中动画
    if let cell = collectionView.cellForItem(at: indexPath) as? CustomCellClass {
        cell.updateSelectionAnimation(isSelected: true)
    }
}

// 可选:处理取消选中的动画
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if let cell = collectionView.cellForItem(at: indexPath) as? CustomCellClass {
        cell.updateSelectionAnimation(isSelected: false)
    }
}

内容的提问来源于stack exchange,提问作者cevhers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:10:18