Как вы знаете, в представлении коллекции и в виде таблицы возникает проблема с повторным использованием ячеек, поэтому каждый раз, когда я прокручиваю видео, статус моего процессора поднимается до 200+. Что вредно для здоровья мобильных телефонов.
Я исходю из логики, которая гласит: я добавляю логику воспроизведения и паузы к действию кнопки, но не знаю, как добавить логику воспроизведения и паузы. в моей кнопке, потому что у меня есть кнопка в ячейках xib-файла, поэтому мне нужно решение для высокой нагрузки на процессор. Может ли кто-нибудь мне помочь?
У меня есть этот код для ячейки представлений моей коллекции: - импортировать UIKit
импортировать AVFoundation
класс VideoCollectionViewCell: UICollectionViewCell {
Код: Выделить всё
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
var playPauseButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Setup player layer
playerLayer = AVPlayerLayer()
playerLayer?.videoGravity = .resizeAspect
contentView.layer.addSublayer(playerLayer!)
// Setup play/pause button
playPauseButton = UIButton(type: .system)
playPauseButton.setTitle("Play", for: .normal)
playPauseButton.addTarget(self, action: #selector(playPauseTapped), for: .touchUpInside)
contentView.addSubview(playPauseButton)
// Layout button
playPauseButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
playPauseButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
playPauseButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
playPauseButton.widthAnchor.constraint(equalToConstant: 100),
playPauseButton.heightAnchor.constraint(equalToConstant: 50)
])
}
override func layoutSubviews() {
super.layoutSubviews()
playerLayer?.frame = contentView.bounds
}
func configure(with url: URL) {
player = AVPlayer(url: url)
playerLayer?.player = player
}
@objc func playPauseTapped() {
if player?.timeControlStatus == .playing {
pause()
} else {
play()
}
}
func play() {
player?.play()
playPauseButton.setTitle("Pause", for: .normal)
}
func pause() {
player?.pause()
playPauseButton.setTitle("Play", for: .normal)
}
override func prepareForReuse() {
super.prepareForReuse()
player?.pause()
playerLayer?.player = nil
}
import UIKit
Класс ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
Код: Выделить всё
@IBOutlet weak var collectionView: UICollectionView!
var videoURLs: [URL] = [/* Your video URLs here */]
var currentlyPlayingIndex: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "VideoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "VideoCell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return videoURLs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! VideoCollectionViewCell
cell.configure(with: videoURLs[indexPath.item])
if indexPath == currentlyPlayingIndex {
cell.play()
} else {
cell.pause()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let currentIndex = currentlyPlayingIndex, let currentCell = collectionView.cellForItem(at: currentIndex) as? VideoCollectionViewCell {
currentCell.pause()
}
let cell = collectionView.cellForItem(at: indexPath) as! VideoCollectionViewCell
cell.play()
currentlyPlayingIndex = indexPath
}
// Ensuring that the video continues playing even when the cell goes off-screen
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let currentlyPlayingIndex = currentlyPlayingIndex else { return }
if let cell = collectionView.cellForItem(at: currentlyPlayingIndex) as? VideoCollectionViewCell {
// Ensure the cell keeps playing the video if it's the currently playing index
cell.play()
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... ew-inswift
Мобильная версия