利用 UIImageView 的 animationImages
顯示幀動畫犬钢,每個 cell 上都顯示贞滨,經(jīng)過測試别瞭,會出現(xiàn)如下幾個問題:
- 滑動 collectionView 后部分 cell 上的 imageView 不再播放動畫
- 點按 cell 跳轉(zhuǎn)到另一個界面战虏,再返回,這個 cell 上的 imageView 不再播放動畫
解決:
在自定義 UICollectionViewCell 中加代碼:
override func prepareForReuse() {
super.prepareForReuse()
endPlayImages()
}
var images: [UIImage]? // cell 緩存 images
func playImages(_ images: [UIImage]? = nil) {
if images != nil {
self.images = images
}
guard let imgs = self.images else {
return
}
previewIV.animationImages = imgs
previewIV.animationDuration = TimeInterval(imgs.count * 1)
previewIV.highlightedAnimationImages = imgs
previewIV.startAnimating()
}
func endPlayImages() {
previewIV.stopAnimating()
}
然后到 UIViewController 中添加代碼:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playAllImages() // 點到別的界面柄冲,返回,需要重新播放動畫
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
playAllImages() // 滑動后重新播放動畫
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
playImage(collectionView: collectionView, indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
playImage(collectionView: collectionView, indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
playImage(collectionView: collectionView, indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
playImage(collectionView: collectionView, indexPath: indexPath)
}
}
extension ViewController {
func playAllImages() {
let visibleCellIndex = self.galleryTypesView.locolCollection.indexPathsForVisibleItems
for (i,cell) in self.galleryTypesView.locolCollection.visibleCells.enumerated() {
let indexPath = visibleCellIndex[i]
if localWorks[indexPath.row].type == .animation {
let cardCell = cell as! CardCollectionCell
cardCell.playImages()
}
}
}
func playImage(collectionView: UICollectionView, indexPath: IndexPath) {
let cardCell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionCell.description(), for: indexPath) as! CardCollectionCell
cardCell.playImages()
}
}