表格视图滚动后播放/暂停按钮图像发生变化

Posted

技术标签:

【中文标题】表格视图滚动后播放/暂停按钮图像发生变化【英文标题】:play/Pause button image changes after Table view scrolling 【发布时间】:2019-12-14 15:15:41 【问题描述】:

我在 tableView 单元格中添加了一个按钮,通过该按钮可以在AVPlayer 中播放音乐 URL。我可以播放音乐,但问题是当我点击播放时它会变为暂停,当我向下滚动并返回顶部时它会再次播放。它没有保持按钮的状态。

当我点击任何单元格的播放按钮时,我希望其他单元格的另一个按钮也应该返回播放图标,以免发生重叠。

这是我的按钮操作代码。我在单元格的类中使用委托来访问此按钮IBAction

extension HomeViewController: RadiocellDelegate 
  func playButtonTapped(cell: RadioCell) 
    guard let indexpath =
      self.listRadioTavleView.indexpathForView(cell.playButton)
    else  return 

    cell.playButton.tag = indexpath.row

    // IF Play Button
    if cell.playButton.currentImage = UIImage(named: "play_icon") 
      loadRadio(radioURL: musicURL[indexpath.row])
      cell.playButton.setImage(UIImage(named: "pause_icon"), for: .normal)
     else  // IF PAUSE BUTTON
      cell.playButton.setImage(UIImage(named: "play_icon"), for: .normal)
      player.pause()
      pause = true
    
  

【问题讨论】:

【参考方案1】:

您不需要存储当前正在播放的单元格索引。在“currentPlayingIndex”类中获取一个全局变量。

let currentPlayingIndex : Int?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 
-> UITableViewCell 
    //Your other code

    cell.tag = indexPath.row
    if let playingCell = currentPlayingIndex 
        if playingCell == indexPath.row 
            cell.playButton.currentImage = UIImage(named: "play_icon")
         else 
            cell.playButton.setImage(UIImage(named: "pause_icon"), for: 
            .normal)
        
    


func playButtonTapped(cell : RadioCell) 
     if currentPlayingIndex == cell.tag 
        player.pause()
        self.pause = true
        currentPlayingIndex = nil
      else  //IF PAUSE BUTTON
        loadRadio(radioURL : musicURL[cell.tag])
        currentPlayingIndex = cell.tag
     
    tableView.reloadData()
 

【讨论】:

我也面临同样的问题【参考方案2】:

我建议您使用基于模型的状态管理。假设你有一个 model 用于渲染 tableview。

struct model 
 var videoURL:String?

   //Add a variable to handle UI
   var isVideoPlaying:Bool? = false

在表格视图单元格中

func playButtonTapped(cell: RadioCell) 
    guard let indexpath = self.listRadioTavleView.indexpathForView(cell.playButton) else 
        return
    
    If model[indexPath.row].isVideoPlaying 
        model[indexPath.row].isVideoPlaying = false
        // add  pausing video and button image changing code

     else 
        model[indexPath.row].isVideoPlaying = true
        // add  playing video and button image changing code
    
    self.listRadioTavleView.reloadData()

【讨论】:

以上是关于表格视图滚动后播放/暂停按钮图像发生变化的主要内容,如果未能解决你的问题,请参考以下文章

当 AVAudioPlayer 完成播放时切换 tableview 单元格图像

从 JSON 中的 URL 加载的图像视图在滚动时发生变化

表格视图高度之外的行的单元格内容发生变化(要查看此单元格,我们向下滚动)?

UITableview 单元格高度在 iOS 14.0 中的滚动表视图上发生变化

重新加载单元格高度变化的单元格时,UITableView 滚动到顶部

滚动表格视图后出现图像 (AFNetworking)