在 Tableview 上滚动时按钮图像发生变化

Button image changes while scrolling on Tableview

我需要认真的帮助,因为我正在 Tableview 上播放音频并使用 AVPlayer 管理 (Play/pause/stop) 它。所有功能都运行良好。

但问题是如何在滚动时只管理 TableView 中的按钮图像? 主要有两点需要考虑

这是 PlayerCell class

   class PlayerCell: UITableViewCell {
        @IBOutlet weak var play_pauseButton: UIButton!
        @IBOutlet weak var txtLabel: UILabel!
    }

可以做的是在配置单元格时重置所有图像。因为 tableView 正在重复使用单元格,所以某些属性在上次更改时会保留下来。如果这是问题所在,代码可以修复为:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerCell
    cell.txtLabel.text = menuArray[indexPath.item]

    cell.play_pauseButton.tag = indexPath.row

    if player?.isPlaying == true && indexPath.row == previous { //Sets the "media-pause" image to the currently played cell
        cell.play_pauseButton.setImage(UIImage(named: "media-pause"), for: .normal)
    } else { //Every other cell that is not the playing one is reseted to the "play-button" image
        cell.play_pauseButton.setImage(UIImage(named: "play-button"), for: .normal)
    }

    return cell
}