swiftAVPlayerLayer视频进度条如何操作纯代码详细点要在TableViewCell里面放视频和进度条视频铺满整个Cell进度条距离底部20位置。宽度为300。视频播放进度要和进度条同步。拖动进度条也要和视频播放同步
要在TableViewCell中放置视频和进度条,并且让视频铺满整个Cell,进度条距离底部20位置,宽度为300,并且让视频播放进度和进度条同步,以及拖动进度条也和视频播放同步,可以按照以下步骤进行操作:
- 创建一个自定义的TableViewCell类,继承自UITableViewCell,并添加一个AVPlayerLayer属性和一个UIProgressView属性。
class VideoTableViewCell: UITableViewCell {
var playerLayer: AVPlayerLayer!
var progressView: UIProgressView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// 初始化AVPlayerLayer
playerLayer = AVPlayerLayer()
playerLayer.videoGravity = .resizeAspectFill
contentView.layer.addSublayer(playerLayer)
// 初始化UIProgressView
progressView = UIProgressView()
progressView.progressTintColor = .green
contentView.addSubview(progressView)
}
override func layoutSubviews() {
super.layoutSubviews()
// 设置AVPlayerLayer的frame
playerLayer.frame = contentView.bounds
// 设置UIProgressView的frame
progressView.frame = CGRect(x: (contentView.bounds.width - 300) / 2, y: contentView.bounds.height - 20, width: 300, height: 2)
}
}
- 在UITableView的dataSource方法中,为每个TableViewCell设置AVPlayerLayer和UIProgressView,并且将视频播放进度和进度条同步。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoTableViewCell", for: indexPath) as! VideoTableViewCell
// 创建AVPlayer
let player = AVPlayer(url: URL(string: "your_video_url")!)
cell.playerLayer.player = player
// 监听视频播放进度
player.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 1), queue: DispatchQueue.main) { time in
let currentTime = CMTimeGetSeconds(time)
let duration = CMTimeGetSeconds(player.currentItem!.duration)
let progress = Float(currentTime / duration)
// 更新进度条进度
cell.progressView.setProgress(progress, animated: true)
}
return cell
}
- 如果需要实现拖动进度条也和视频播放同步,可以添加一个拖动结束的事件,来更新视频播放进度。
progressView.addTarget(self, action: #selector(progressSliderValueChanged), for: .valueChanged)
@objc func progressSliderValueChanged() {
let duration = CMTimeGetSeconds(player.currentItem!.duration)
let targetTime = duration * Double(progressView.value)
let time = CMTimeMakeWithSeconds(targetTime, preferredTimescale: 1)
player.seek(to: time)
}
以上是纯代码实现在TableViewCell中放置视频和进度条,并且让视频播放进度和进度条同步,以及拖动进度条也和视频播放同步的详细步骤。你可以根据自己的需求进行修改和调整
原文地址: https://www.cveoy.top/t/topic/h9LR 著作权归作者所有。请勿转载和采集!