在使用AVPlayer播放视频的UITableView单元格中,确保AVPlayer在单元格被回收之前停止播放,可以按照以下步骤进行操作:
class CustomTableViewCell: UITableViewCell {
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
// ...
}
class CustomTableViewCell: UITableViewCell {
// ...
override func prepareForReuse() {
super.prepareForReuse()
// 在单元格被复用之前停止播放
player?.pause()
playerLayer?.removeFromSuperlayer()
// 清空player和playerLayer
player = nil
playerLayer = nil
}
}
cellForRowAt中,为每个单元格创建AVPlayer和AVPlayerLayer,并开始播放。func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
// 创建AVPlayer对象
let videoURL = URL(string: "your_video_url")
let player = AVPlayer(url: videoURL!)
cell.player = player
// 创建AVPlayerLayer对象
let playerLayer = AVPlayerLayer(player: player)
cell.playerLayer = playerLayer
// 设置playerLayer的frame
playerLayer.frame = cell.contentView.bounds
cell.contentView.layer.addSublayer(playerLayer)
// 播放视频
player.play()
return cell
}
这样,每次单元格被复用时,会停止之前的AVPlayer的播放并移除AVPlayerLayer,然后为新的单元格创建AVPlayer和AVPlayerLayer并开始播放视频。