ios - 为什么动画不起作用但打印语句有效?

标签 ios swift

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/

相关文章:

ios - Swift 3 升级问题转换

Xcode 将构建/运行但存档失败并显示 "No such module Google"- Swift iOS

swift - #selector 在 Swift 4 中不起作用?

ios - 未在 UICollectionViewCell 中的 UILabel(或 UITextField)中设置文本

ios - 在 CocoaPods 0.39.0 上运行 pod update 时发出警告

ios - 无法获取 numberOfLines = 0 的 UILabel 的高度

ios - 如何滚动库比蒂诺选取器自动 flutter ?

ios - UICollectionView 的不可见单元格保持选中状态

ios - AnyObject 到 swift 字符串

ios - dyld : Library not loaded: @rpath/libswiftCoreAudio. dylib 引用自:<Framework> 原因:找不到图像