当转到新的 UIViewController 并返回时,UICollectionViewCell 动画停止

UICollectionViewCell animation stops when segued to a new UIViewController and back

我在 UICollectionView 中有一个自定义 UICollectionViewCell,它在最初显示集合视图时可以正确设置动画。然而,当我进入一个新的 UIViewController 并回到原来的 UIViewController 时,动画停止了。

class EmptyDishesCollectionViewCell: UICollectionViewCell {

  @IBOutlet weak var plateImage: UIImageView!
  @IBOutlet weak var knifeImage: UIImageView!
  @IBOutlet weak var forkImage: UIImageView!

  @IBOutlet weak var emptyBackgroundView: UIView!
  @IBOutlet weak var plateHeight: NSLayoutConstraint!
  @IBOutlet weak var plateWidth: NSLayoutConstraint!

  override func awakeFromNib() {
    super.awakeFromNib()
    setupBorders()
    setupImages()
    beginAnimation()
    setShadow()
  }

  func setupBorders() {
    self.emptyBackgroundView.layer.cornerRadius = 3.0
    self.emptyBackgroundView.backgroundColor = UIColor.white
  }

  func setupImages() {
    self.plateImage.tintColor = UIColor.projectBackgroundSuperLightGray
    self.forkImage.tintColor = UIColor.projectBackgroundSuperLightGray
    self.knifeImage.tintColor = UIColor.projectBackgroundSuperLightGray
  }

  func beginAnimation() {
    UIView.animateKeyframes(withDuration: 2.4, delay: 0.0, options: [.calculationModeLinear, .repeat, .autoreverse], animations: {
      UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 2/5, animations: {
        let moveLeft = CGAffineTransform(translationX: -5.0, y: 0.0)
        let moveRight = CGAffineTransform(translationX: 5.0, y: 0.0)
        let rotate = CGAffineTransform(rotationAngle: .pi / 5.0)
        self.forkImage.transform = moveLeft
        self.knifeImage.transform = moveRight
        self.plateImage.transform = rotate
      })
      UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 1/5, animations: {
//        let wait = CGAffineTransform(translationX: -5.0, y: 0.0)
//        self.forkImage.transform = wait
      })
      UIView.addKeyframe(withRelativeStartTime: 2/3, relativeDuration: 2/5, animations: {
        self.forkImage.transform = .identity
        self.knifeImage.transform = .identity
        self.plateImage.transform = .identity
      })
    })
  }
}

我假设当视图移出视线时,动画会自动停止,但是当它重新进入视图时需要手动再次启动。

所以我很自然地认为将动画块放入 didMoveToWindow 会解决它,但这是不行的。

如有任何帮助,我们将不胜感激

你的viewWillAppear(animated)中的collectionView.reloadData()怎么样?我猜这不会有帮助,除非你在你的 cellForItemAt.

中调用你的 beginAnimation()

所以您在 awakeFromNib()

中调用 beginAnimation()

发件人:

awakeFromNib gets called after the view and its subviews were allocated and initialized. It is guaranteed that the view will have all its outlet instance variables set.

我建议您在 cellForItemAt 期间调用 EmptyDishesCollectionViewCellbeginAnimation() 函数。如有必要,只需重新加载 collectionView。希望对你有帮助!