Swift Dynamic animation followed by property animator

149 views Asked by At

I have an animation where I use a push animation, then a snap animation using UIDynamicBehavior, and then I finish with a property behavior:

for card in selectedCards {
        removeCard(card: card)
      }

  private func removeCard(card: Card) {
    guard let subView = cardsContainer.subviews.first(where: { ($0 as? PlayingCardView)?.card == card }) else {
      return
    }
    if let card = subView as? PlayingCardView { card.selected = false }
    let matchedCardsFrame = matchedCards.convert(matchedCards.frame, to: view)
    view.addSubview(subView)
    cardBehavior.addItem(subView) // here I add the push behavior
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
      self.cardBehavior.removeItem(subView) // here I remove the push behavior
      UIViewPropertyAnimator.runningPropertyAnimator(
        withDuration: 0.3,
        delay: 0,
        options: [],
        animations: {
          self.cardBehavior.addSnapBehavior(subView, frame: matchedCardsFrame) // here I add the snap behavior
      }, completion: { finished in
          self.animator.removeAllBehaviors()
          subView.frame.size = CGSize(width: matchedCardsFrame.height, height: matchedCardsFrame.width)
          subView.transform = CGAffineTransform.identity.rotated(by: CGFloat.pi / 2)
          subView.setNeedsDisplay()
      })
    }
  }

Essentially the above code does the following:

  • Add push behavior
  • Remove push behavior
  • Add snap behavior
  • Remove all behaviors
  • Add property transform

What I want is for the push action to execute, then after a second or so, have the snap behavior execute, and after the snap execution is finished, to perform a transform. However, if I removeAllBehaviors() before I execute the property transform then the snap behavior doesn't finish. But if I leave the snap behavior and try to execute the property transform then it has no effect since it appears that the snap behavior acts on the object indefinitely, putting it at odds with the property transform.

How can I programmatically say finish the snap behavior and then perform the transform?

0

There are 0 answers