Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用Swift在tableviewcell中播放和停止AVPlayer_Ios_Swift_Iphone - Fatal编程技术网

Ios 使用Swift在tableviewcell中播放和停止AVPlayer

Ios 使用Swift在tableviewcell中播放和停止AVPlayer,ios,swift,iphone,Ios,Swift,Iphone,我的应用程序聊天页面是一个表视图,每个单元格都有一个AVPlayer和一个AVPlayServiceWController。问题是我可以在多个单元格上单击播放,它们都将同时播放。我正试图弄清楚当点击任何播放按钮时,如何暂停其他单元格 let playerItem = AVPlayerItem(url: URL(string: dict1.voiceURL!)!) avPlayer = AVPlayer.init(playerItem: playerItem) avPlayer!.pause()

我的应用程序聊天页面是一个表视图,每个单元格都有一个AVPlayer和一个AVPlayServiceWController。问题是我可以在多个单元格上单击播放,它们都将同时播放。我正试图弄清楚当点击任何播放按钮时,如何暂停其他单元格

let playerItem = AVPlayerItem(url: URL(string: dict1.voiceURL!)!)
avPlayer = AVPlayer.init(playerItem: playerItem)
avPlayer!.pause()
cell!.playerViewController = AVPlayerViewController()
cell!.playerViewController?.showsPlaybackControls = true
cell!.playerViewController.view.backgroundColor = .clear
cell!.playerViewController.player = avPlayer
cell!.playerViewController.view.frame = CGRect(x: 0, y: 0, width: cell!.PlayerView_1.frame.size.width, height: cell!.PlayerView_1.frame.size.height)
cell!.playerViewController.player?.pause()
self.addChildViewController(cell!.playerViewController)
cell?.PlayerView_1.addSubview(cell!.playerViewController.view)

请帮忙,因为我在这个领域很新。谢谢。

您只需要声明两个变量,它们存储上次选中的和当前选中的索引,如下所示

    var lastSelectedRow: IndexPath?
        var currentlySelectedRow: IndexPath?
        
            override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    if let cell = tableView.cellForRow(at: indexPath) as? YourClass
            {
                cell.playVideo()
            }
            
            if let lastCell = tableView.cellForRow(at: lastSelectedRow) as? YourClass
            {
                lastCell.pauseVideo()
            }
    
                super.tableView(tableView, didSelectRowAt: indexPath)
                lastSelectedRow = currentlySelectedRow
                currentlySelectedRow = indexPath

tableView.reloadRows(at: [lastSelectedRow], with: .automatic)

            }

当我们点击avplayer控制器的播放按钮时,选择Rowat not called