import UIKit
protocol Shakeable {}
extension Shakeable where Self: UIView {
func shake() {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.5
animation.repeatCount = 5
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 4 , y: self.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 4, y: self.center.y))
layer.add(animation, forKey: "position")
print("Shaked!")
}
}
然后我有一个自定义单元模型,我在其中实现了这个协议(protocol)。然后我在我的 Controller 中调用 func
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TacoCell", for: indexPath) as? TacoCell {
cell.shake()
}
}
我是编码新手,所以请原谅我提出问题的糟糕方式。
最佳答案
这是你的问题行:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TacoCell", for: indexPath) as? TacoCell {
您正在出列一个新 单元格,而不是获取已经存在的单元格。
您应该使用 cellForItem(at:)
- 这会获取已存在的单元格实例。
例如
if let cell = cellForItem(at: indexPath) as? TacoCell {
cell.shake()
}
关于ios - 为什么动画不起作用但打印语句有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336456/