要在TableViewCell中放置视频和进度条,并且让视频铺满整个Cell,进度条距离底部20位置,宽度为300,并且让视频播放进度和进度条同步,以及拖动进度条也和视频播放同步,可以按照以下步骤进行操作:\n\n1. 创建一个自定义的TableViewCell类,继承自UITableViewCell,并添加一个AVPlayerLayer属性和一个UIProgressView属性。\n\nswift\nclass VideoTableViewCell: UITableViewCell {\n var playerLayer: AVPlayerLayer!\n var progressView: UIProgressView!\n \n override 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()\n progressView.progressTintColor = .green\n contentView.addSubview(progressView)\n }\n \n override func layoutSubviews() {\n super.layoutSubviews()\n \n // 设置AVPlayerLayer的frame\n playerLayer.frame = contentView.bounds\n \n // 设置UIProgressView的frame\n progressView.frame = CGRect(x: (contentView.bounds.width - 300) / 2, y: contentView.bounds.height - 20, width: 300, height: 2)\n }\n}\n\n\n2. 在UITableView的dataSource方法中,为每个TableViewCell设置AVPlayerLayer和UIProgressView,并且将视频播放进度和进度条同步。\n\nswift\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: "VideoTableViewCell", for: indexPath) as! VideoTableViewCell\n \n // 创建AVPlayer\n let player = AVPlayer(url: URL(string: "your_video_url")!)\n cell.playerLayer.player = player\n \n // 监听视频播放进度\n player.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 1), queue: DispatchQueue.main) { time in\n let currentTime = CMTimeGetSeconds(time)\n let duration = CMTimeGetSeconds(player.currentItem!.duration)\n let progress = Float(currentTime / duration)\n \n // 更新进度条进度\n cell.progressView.setProgress(progress, animated: true)\n }\n \n return cell\n}\n\n\n3. 如果需要实现拖动进度条也和视频播放同步,可以添加一个拖动结束的事件,来更新视频播放进度。\n\nswift\nprogressView.addTarget(self, action: #selector(progressSliderValueChanged), for: .valueChanged)\n\n@objc func progressSliderValueChanged() {\n let duration = CMTimeGetSeconds(player.currentItem!.duration)\n let targetTime = duration * Double(progressView.value)\n let time = CMTimeMakeWithSeconds(targetTime, preferredTimescale: 1)\n \n player.seek(to: time)\n}\n\n\n以上是纯代码实现在TableViewCell中放置视频和进度条,并且让视频播放进度和进度条同步,以及拖动进度条也和视频播放同步的详细步骤。你可以根据自己的需求进行修改和调整。

Swift AVPlayerLayer 视频进度条 实战教程:在 TableViewCell 中实现视频播放与进度同步

原文地址: https://www.cveoy.top/t/topic/pSx7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录