取消更改控制器时,表格视图单元格内的 Swift Avplayer 仍在播放

Mar*_*rco 5 uitableview ios avplayer swift

我在我的 tableview 单元格中配置了一个 avPlayer:

func createPlayer(url: URL) {
    self.playerCell = AVPlayer(url: url)
    self.videoContainerView.playerLayer.bounds = self.videoContainerView.bounds
    self.videoContainerView.playerLayer.videoGravity = .resizeAspectFill
    self.videoContainerView.playerLayer.player = playerCell
     playerCell?.play()
}
Run Code Online (Sandbox Code Playgroud)

每当用户单击按钮时调用此函数

@IBAction func playBtnPressed(_ sender: Any) {
    if let videoUrlString = post?.mediaUrl, let url = URL(string: videoUrlString) {
        createPlayer(url: url)
    }
    playBtn.isHidden = true
}
Run Code Online (Sandbox Code Playgroud)

在我的 tableview 控制器中,只要不再显示单元格,我就可以停止播放器,如下所示:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as? VideoCell else {return}
    if cell.playerCell != nil {
        if (cell.playerCell?.rate != 0) && (cell.playerCell?.error == nil) {
            cell.playerCell?.pause()
            cell.playerCell = nil
            cell.playBtn.isHidden = false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果从 tableview 控制器切换到另一个控制器或关闭控制器,视频仍在播放。我怎样才能停止播放器?

我需要索引路径来识别播放器,因此我无法调用 viewWillDisappear 中的函数。

希望有人能帮忙,我已经尝试解决这个问题 3 天了...

谢谢!---------------------- 更新我尝试这样做:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
 guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? VideoCell else {return}
    if cell.playerCell != nil {
        if (cell.playerCell?.rate != 0) && (cell.playerCell?.error == nil) {
            cell.playerCell?.pause()
            cell.playerCell = nil
            cell.playBtn.isHidden = false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用......

mat*_*att 6

实现viewWillDisappear调用visibleCells并循环它们以查找 VideoCell。每次你找到一个,就告诉它停止播放,就像你已经拥有的代码一样。