我正在尝试在UICollectionView的每个单元中模拟闪烁的动画。
当我启动应用程序时,它可以正常工作:
但是当我向左滚动时,每个单元格都会获得动画:
我想要的是,当我向左滚动时,它的工作原理类似于第一张图像。有一阵子,我只是将下面的代码放在动画中:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? ShimmeringCell else { return }
UIView.animate(withDuration: 1.0, delay: 0, options: [.autoreverse, .repeat], animations: {
cell.alpha = 0.4
}, completion: nil)
}
这是完整代码:Github
有人可以帮我吗?
我找到了答案。
为了解决此问题,我必须创建一个新的UIView
并将其添加到UICollectionView
的子视图中:
let newCollectionView: UICollectionView = {
// Here was creating a collectionView
return collection
}()
let viewExample: UIView = {
// Here was creating a new view
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
newCollectionView.delegate = self
newCollectionView.dataSource = self
newCollectionView.register(ShimmeringCell.self, forCellWithReuseIdentifier: cellId)
self.view.addSubview(self.newCollectionView)
setupCollection()
}
private func setupCollection() {
// Constraints...
self.newCollectionView.addSubview(self.viewExample)
setupViewExample()
}
private func setupViewExample() {
// Constraints...
}
之后,我只是将动画放在此视图中:
override func viewDidLoad() {
super.viewDidLoad()
newCollectionView.delegate = self
newCollectionView.dataSource = self
newCollectionView.register(ShimmeringCell.self, forCellWithReuseIdentifier: cellId)
self.view.addSubview(self.newCollectionView)
setupCollection()
self.viewExample.alpha = 0.6
UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction], animations: {
self.viewExample.alpha = 0
}, completion: nil)
}
结果:
感谢所有人,在世界的某个地方见到您。
具有此解决方案的Github:Github