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

Swift如何将UITableView Cell选中动画迁移到自定义Cell类中

实现步骤
  • 第一步:在自定义UITableViewCell类中新增公开的动画方法,将缩放逻辑封装在内
class CustomTableViewCell: UITableViewCell {
    // 其他自定义Cell的原有逻辑
    
    // 封装的选中缩放动画方法
    func startSelectScaleAnimation() {
        UIView.animate(withDuration: 0.2, animations: { [weak self] in
            self?.transform = CGAffineTransform(scaleX: 0.97, y: 0.97)
        }, completion: { [weak self] finished in
            guard finished else { return }
            UIView.animate(withDuration: 0.2) {
                self?.transform = .identity
            }
        })
    }
}

这里用[weak self]避免循环引用,同时避免Cell提前释放时强制解包引发的崩溃。

注意:需要确保UITableView注册的Cell类、Cell复用标识对应你自定义的Cell类,否则类型转换会失败,动画无法触发。

  • 第二步:修改原有的tableView(_:didSelectRowAt:)代理方法,直接调用Cell的封装方法即可
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell else { return }
    cell.startSelectScaleAnimation()
    // 其余原有选中后的业务逻辑保持不变
}
可选优化

如果你希望Cell在被长按高亮时也自动触发对应效果,可以重写Cell的isHighlighted属性:

override var isHighlighted: Bool {
    didSet {
        if isHighlighted {
            transform = CGAffineTransform(scaleX: 0.97, y: 0.97)
        } else {
            UIView.animate(withDuration: 0.2) {
                self.transform = .identity
            }
        }
    }
}

这样就不需要在代理方法里手动调用动画方法,高亮状态变化时会自动触发缩放效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:30:01