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

Swift iOS:如何清理Cell的类属性及内部ImageView的图片?

我在项目里同时用到了CollectionViewCell和TableViewCell,不过这次只针对TableViewCell展开说明——毕竟这两类Cell都会触发prepareForReuse()方法,复用逻辑上是共通的。

先贴出我的Cell核心实现代码:

class CustomVideoTableViewCell: UITableViewCell {
    // 界面控件关联
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var backgroundViewForPlayerLayer: UIView!
    
    // 业务数据与播放状态属性
    var data: MyData?
    var currentTime: CMTime? // 专门用来在App退到后台时记录视频当前播放时长
    var playerItem: AVPlayerItem?
    
    // 重写复用方法,清理旧状态是核心
    override func prepareForReuse() {
        super.prepareForReuse()
        
        // 重置文本显示
        titleLabel.text = nil
        // 清理播放器相关资源,避免复用后出现播放状态串线
        playerItem?.cancelPendingSeeks()
        playerItem = nil
        currentTime = nil
        // 重置图片
        thumbnailImageView.image = nil
        // 移除容器内的PlayerLayer,避免残留
        backgroundViewForPlayerLayer.subviews.forEach {
            if $0 is AVPlayerLayer {
                $0.removeFromSuperview()
            }
        }
    }
}

这里必须强调prepareForReuse()的重要性:Cell复用机制会让旧Cell被重新分配给新数据,如果不在这里做好状态清理,很容易出现各种诡异bug——比如旧的播放时长被带到新Cell里,或者之前的图片、文本没清干净导致显示错乱。尤其是涉及视频播放这类带状态的控件,一定要在复用前把旧的PlayerItem、播放进度这些都彻底清理,不然很容易出现播放串流、界面残留的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:58