利用 UIImageView 的 animationImages
显示帧动画,每个 cell 上都显示,经过测试,会出现如下几个问题:
- 滑动 collectionView 后部分 cell 上的 imageView 不再播放动画
- 点按 cell 跳转到另一个界面,再返回,这个 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()
}
}
网友评论