ios - 如何在 UITableViewCell 中处理 AVPlayer?

标签 ios swift

我正在尝试研究如何在 UITableViewCell 中成功使用 AVPlayer。在我的 UITableViewCell 中,我有一个 UIView 子类,其中有一个 AVPlayerLayer 使用此代码(Apple 提供):

class PlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
         return layer as! AVPlayerLayer
    }

    override class var layerClass : AnyClass {
         return AVPlayerLayer.self
    }

}

我使用以下代码在 -cellForRowAtIndexPath: 中设置了 player:

let videoPlayer = AVPlayer(playerItem: AVPlayerItem(asset: cellVideo))
cell.playerView.player = videoPlayer

这工作正常,但是,当单元格不在 View 中时,我不想播放视频。我应该将 player 设置为 nil,然后在单元格再次显示时再次设置 player,还是应该暂停视频?或者我应该使用另一种方式吗?

最佳答案

编辑

是的,您应该将播放器设置为 nil 以提高性能。 我认为您还应该通过重写 prepare for reuse 方法在自定义单元类中将播放器设置为 nil。

override func prepareForReuse() {
    player = nil
    super.prepareForReuse()
}

此外,如果您的目标是模仿新闻源行为,我建议您查看 AVPlayer:PrerollAtRate它让您在特定时间竖起大拇指。


您可以使用委托(delegate)方法来暂停和恢复播放器。 只需确保将 UITableViewCell 转换为您的自定义类即可

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    //cast the cell as your custom cell
    if let myCell = cell as? MyCustomCell
    {
        myCell.player!.play()
    }

}


func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    //cast the cell as your custom cell
    if let myCell = cell as? MyCustomCell
    {
        myCell.player!.pause()
    }

}

关于ios - 如何在 UITableViewCell 中处理 AVPlayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40870916/

相关文章:

ios - 将控制命令发送到 UIWebView 以进行在线游戏 - Swift

swift - 如何更改窗口的内容 View ?

ios - Cloud Firestore - 循环 getDocument 请求(500 多个文档)性能低下(Swift)

ios - 从 iOS 应用程序中的 S3 存储桶中删除文件 (Swift)

ios - 延迟更改 viewWillAppear 中的 navigationBar.barTintColor

ios - 有没有办法从一个大的对象列表中只加载几个项目并填充到 UICollectionView 中

ios - 升级到 iOS 9 和 MobileFirst 7.1 后无法在设备或模拟器上登录应用程序

ios - iOS版Flutter ImageCrop库相机权限错误

iphone - 以编程方式将 UITabBarItem 添加到 UITabBar,并为其设置操作

ios - 如何更改表单内的 NavigationLink 箭头颜色