Swift - AVPlayerLayer 视频进度条:在 TableViewCell 中实现视频播放和进度条同步
以下是一个示例的纯代码实现,使用 AVPlayerLayer 和 UIProgressView 来实现在 TableViewCell 中放置视频和进度条,并确保视频播放进度和进度条同步。\n\n首先,在 TableViewCell 的类中定义一个 AVPlayerLayer 和 UIProgressView 的实例变量:\n\nswift\nclass VideoTableViewCell: UITableViewCell {\n var playerLayer: AVPlayerLayer!\n var progressView: UIProgressView!\n \n // ...\n}\n\n\n然后,在 TableViewCell 的初始化方法中创建 AVPlayerLayer 和 UIProgressView,并设置其属性:\n\nswift\noverride init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {\n super.init(style: style, reuseIdentifier: reuseIdentifier)\n \n // 创建 AVPlayerLayer\n playerLayer = AVPlayerLayer()\n playerLayer.videoGravity = .resizeAspectFill\n contentView.layer.addSublayer(playerLayer)\n \n // 创建 UIProgressView\n progressView = UIProgressView(progressViewStyle: .default)\n progressView.trackTintColor = UIColor.gray\n progressView.progressTintColor = UIColor.blue\n contentView.addSubview(progressView)\n \n // 设置进度条位置和尺寸\n progressView.translatesAutoresizingMaskIntoConstraints = false\n NSLayoutConstraint.activate([\n progressView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),\n progressView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),\n progressView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20),\n progressView.heightAnchor.constraint(equalToConstant: 2)\n ])\n}\n\n\n接下来,在 TableViewCell 中添加一个方法来设置视频播放器和进度条:\n\nswift\nfunc configure(with videoURL: URL) {\n // 创建 AVPlayer\n let player = AVPlayer(url: videoURL)\n playerLayer.player = player\n \n // 监听播放进度\n player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: DispatchQueue.main) { [weak self] time in\n guard let self = self else { return }\n \n let progress = Float(time.seconds / player.currentItem!.duration.seconds)\n self.progressView.setProgress(progress, animated: true)\n }\n}\n\n\n最后,在 TableViewController 中使用这个 TableViewCell,并调用 configure 方法来设置视频播放器和进度条:\n\nswift\nclass ViewController: UITableViewController {\n let videoURLs = [URL(string: "YOUR_VIDEO_URL_HERE")!]\n \n // ...\n \n override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoTableViewCell\n \n let videoURL = videoURLs[indexPath.row]\n cell.configure(with: videoURL)\n \n return cell\n }\n \n // ...\n}\n\n\n这样,每个 TableViewCell 都会有一个铺满整个 Cell 的视频播放器和一个距离底部 20 位置的进度条。视频播放进度将与进度条同步,并且拖动进度条也会同步视频播放进度。
原文地址: https://www.cveoy.top/t/topic/pSyh 著作权归作者所有。请勿转载和采集!