简体   繁体   中英

Dynamically Created UIView Will Not Animate After Collision

thanks for reading this post.

Here is a summary of my program:

  1. I dynamically add a couple UIViews as subviews.

  2. I have objects that move around and collide

  3. When a collision happens I want one of the created UIViews to fade out and then I want to remove one of the collided UIViews.

I am able to remove the created UIView with the following: dynamicAnimator?.referenceView?.viewWithTag(tagOfView)?.removeFromSuperview()

However, when I try to add an animation to fade out the view, I am not getting any type of fade/animation. What am I doing incorrectly?

UIView.animateWithDuration(1.5, animations: {
    self.dynamicAnimator?.referenceView?.viewWithTag(tagOfView)?.alpha = 0.0 
})

In case needed, here is the entire collisionBehavior() function.

func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) {
    let identOpt : NSCopying? = identifier

    if let ident = identOpt as? NSNumber {
        switch ident {
        case Identifiers.paddleAtStartup:
            break
        default:
            ballCollider.removeBoundaryWithIdentifier(ident)
            UIView.animateWithDuration(1.5, animations: {
                self.dynamicAnimator?.referenceView?.viewWithTag(Int(ident))?.alpha = 0.0
                })
            dynamicAnimator?.referenceView?.viewWithTag(Int(ident))?.removeFromSuperview()       
        }
    }
}

You remove view immediately after collision, and there's nothing to animate. You better remove it in animation's completion handler.

Here is the corrected code for anyone with the same problem:

 func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) {
    let identOpt : NSCopying? = identifier

    if let ident = identOpt as? NSNumber {
        switch ident {
        case Identifiers.paddleAtStartup:
            break
        default:
            UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { ()
                self.dynamicAnimator?.referenceView?.viewWithTag(Int(ident))?.alpha = 0.0
                }, completion: {
                    if $0 {
                        self.dynamicAnimator?.referenceView?.viewWithTag(Int(ident))?.removeFromSuperview()
                        self.ballCollider.removeBoundaryWithIdentifier(ident)
                    }
            })
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM