-1

我想在播放音乐时更改单元格图像,当我选择行时,我使用 didselectrow 来更改图像,当我滚动时,我看到许多其他单元格图像也发生了变化,我不知道为什么请指导我这里是我的代码

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          let cell = tableView.cellForRow(at: indexPath) as? NaatListTableViewCell
            cell?.btnPlayPause.setImage(UIImage(named: "pause"), for: .normal)

    }
4

3 回答 3

0

尝试:

var isPlayingIndex = -1
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as? NaatListTableViewCell
    if indexPath.row == isPlayingIndex {
        cell?.btnPlayPause.setImage(UIImage(named: "play"), for: .normal)
    }else {
        cell?.btnPlayPause.setImage(UIImage(named: "pause"), for: .normal)
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as? NaatListTableViewCell
    if indexPath.row == isPlayingIndex {
        cell?.btnPlayPause.setImage(UIImage(named: "pause"), for: .normal)
        isPlayingIndex = -1
    } else {
        // stop current player
        //
        isPlayingIndex = indexPath.row
        cell?.btnPlayPause.setImage(UIImage(named: "play"), for: .normal)
    }
}
于 2019-05-13T10:12:37.340 回答
0

而不是在方法中更改图像,您可以通过在自定义中实现方法并在那里处理图像状态didSelectRowAt来做另一种方式,即setSelected(_:animated:)UITableViewCell

override func setSelected(_ selected: Bool, animated: Bool) {
    if selected {
        btnPlayPause.setImage(UIImage(named: "pause"), for: .normal)
    } else {
        btnPlayPause.setImage(UIImage(named: "play"), for: .normal)
    }
}

上述方法在tableViewinsingle-selectionmulti-selection模式下处理所有单元格的选择和取消选择。

在此之后,您不需要在tableView(_:didSelectRowAt:)方法中编写任何内容。

于 2019-05-13T10:33:39.647 回答
0

您需要手动维护单元格的状态。您可能有一些与您的单元相关联的其他数据,从您所询问的内容来看,它似乎是一个音乐文件列表,您可以将每个音乐与其模型中的唯一 ID 相关联。现在创建一个类型的映射var isPlaying = [Int: Bool]()(假设您使用 int ids)

然后在didSelectRowAt设置对应id的值 self.isPlaying[YOUR_ID] = cell.isSelected

现在在你的cellForRowAt方法中

var imageName = self.isPlaying[YOUR_ID] ? "play" : "pause"
cell?.btnPlayPause.setImage(UIImage(named: imageName), for: .normal)

于 2019-05-13T10:57:20.387 回答