【问题标题】:How to handle tableView cell audio play and pause button using Swift?如何使用 Swift 处理 tableView 单元格音频播放和暂停按钮?
【发布时间】:2018-11-08 04:30:33
【问题描述】:

我的场景,我是 recording audio 和 save 到 Coredata 然后 listing 到 tableView 和 customcell 播放/暂停单个按钮。我不能做下面的事情

  1. 检测playback 的结尾并更改audio play 单元格按钮图像暂停播放
  2. 第一行cell音频播放时间,如果用户点击第二行播放按钮需要stop第一行单元格音频播放并更改图像暂停播放 然后second row单元格按钮播放暂停

以上两个操作怎么做?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CustomCell

        // Configure the cell...            
        cell.likeBtn.addTarget(self, action: #selector(TableViewController.liked), for: .touchUpInside)

        return cell
}

@objc func liked(sender: UIButton) {
        // Here I need to change button icon and handle row
}

【问题讨论】:

    标签: ios swift tableview


    【解决方案1】:

    如果不了解应用程序的其余部分,有点难以解释。提供更多背景信息很重要。假设某些事情,我会尝试给你一个答案。

    首先我假设你有Song 对象,看起来像这样:

    public struct Song: Equatable {
        let name: String
        let fileName: String
    }
    

    您的数据库具有以下公共方法和属性:

    class DB {
      func getSong(_ position: Int) -> Song?
      func getPosition(_ song: Song) -> Int?
      var count: Int
    }
    

    为了方便init 上的这个示例代码,一些预定义数据被初始化。

    还有一个Player 对象使用以下公共方法管理播放音频:

    class Player {
      func currentlyPlaying() -> Song?
      func play(this song: Song)
      func stop()
    }
    

    现在有了这个先前定义,我创建了一个自定义单元格来显示数据库中每个Song 的名称和一个按钮。定义是这样的:

    class CustomCell : UITableViewCell {
      @IBOutlet weak var label: UILabel!
      @IBOutlet weak var button: UIButton!
    }
    

    看起来像:

    接下来让我们定义 tableview 的数据源方法。在每个单元格中,为每个按钮的 touchUpInside 事件添加了一个目标(正如您在问题中定义的那样)。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return DB.shared.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",  
                                               for: indexPath) as! CustomCell
      cell.label.text = DB.shared.getSong(indexPath.row)!.name
      cell.button.addTarget(self, action: #selector(buttonTapped(_:)),
                            for: .touchUpInside)
      return cell
    }
    

    接下来让我们定义一个辅助方法来定位UIVIew 内的TableView。使用这种方法,我们可以获得TableView 中任何单元格内任何控件的IndexPath。返回值是可选的,如果找不到则返回nil。

    func getViewIndexInTableView(tableView: UITableView, view: UIView) -> IndexPath? {
      let pos = view.convert(CGPoint.zero, to: tableView)
      return tableView.indexPathForRow(at: pos)
    }
    

    定义了另一个帮助方法来改变带有动画的按钮的图像:

    func changeButtonImage(_ button: UIButton, play: Bool) {
      UIView.transition(with: button, duration: 0.4,
                        options: .transitionCrossDissolve, animations: {
        button.setImage(UIImage(named: play ? "Play" : "Stop"), for: .normal)
      }, completion: nil
    }
    

    需要一种方法来停止任何当前正在播放的歌曲。首先是检查歌曲是否正在播放,如果是,请调用Player 的停止方法。然后让我们本地化Song在数据库中的位置,在我的例子中对应于TableView中的位置;有了这个让我们创建一个IndexPath来获取对应的单元格,最后用单元格的按钮调用changeButtonImage来改变图像。

    func stopCurrentlyPlaying() {
      if let currentSong = Player.shared.currentlyPlaying() {
        Player.shared.stop()
          if let indexStop = DB.shared.getPosition(currentSong) {
            let cell = tableView.cellForRow(at: IndexPath(item: indexStop, section: 0)) as! CustomCell
            changeButtonImage(cell.button, play: true)
          }
      }
    }
    

    开始播放歌曲的buttonTapped 方法内部有一些逻辑。首先方法签名需要@objc 才能在addTarget 方法中使用。逻辑如下:

    1. 使用辅助方法在表格视图中本地化按钮的IndexPath。
    2. 本地化数据库中的歌曲,表中的行号对应数据库中的顺序。
    3. 如果当前正在播放一首歌曲并且与点击按钮的本地化歌曲相同,则表示我们只想停止歌曲,因此调用stopCurrentlyPlaying 并返回该方法。
    4. 如果不是同一首歌曲或没有播放任何内容,请致电:stopCurrentlyPlaying,开始播放新歌曲并将点击按钮的图像更改为停止图像。

    代码如下所示:

    @objc func buttonTapped(_ sender: UIButton) {
      // Let's localize the index of the button using a helper method
      // and also localize the Song i the database
      if let index = getViewIndexInTableView(tableView: tableView, view: sender),
          let song = DB.shared.getSong(index.row) {
          // If a the song located is the same it's currently playing just stop
          // playing it and return.
          guard song != Player.shared.currentlyPlaying() else {
              stopCurrentlyPlaying()
              return
          }
          // Stop any playing song if necessary
          stopCurrentlyPlaying()
          // Start playing the tapped song
          Player.shared.play(this: song)
          // Change the tapped button to a Stop image
          changeButtonImage(sender, play: false)
      }
    }
    

    这里是示例应用程序运行的小视频:sample app

    【讨论】:

    • 对不起,我忘记与示例代码共享 Github 存储库:github.com/acyrman/StackOverflow53201581
    • 我使用你的代码。它对我也很好。但是当我返回到 tableview 控制器时,播放/停止按钮被重置为播放按钮,但它应该是停止按钮,因为音乐仍在播放。
    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多