Animate UIView horizontally using UIDynamicAnimato

2019-02-11 06:02发布

问题:

I have gone through the documentation, and I am embarrassed to say I am confused.

The Scenario:

I have a UIView, that acts like a container for 3 UIButtons. This container is initially of bounds {0, 0, 35, 35}, with each button inside with the same co-ordinates (with alpha 0). On a specific action by the user, the container changes bounds to {0, 0, 100, 35}, and the button are animated to x-origin 5, 35, and 65, respectively, with alpha 1, such that they are spread out inside the resized container. I refer to this as the expanded state of the container. The same action by the user, toggles it back to the original contracted state.

The Goal:

I am currently doing this using the [UIView animateWithDuration:] block, but would like to use the UIDynamicAnimator to add a bouncy effect, such that, when toggling to expanded state , the container resizes with a bounce (resizes a bit extra, and bounces back to target bounds), and the buttons bounce as well (move a bit further, and bounce back to their target bounds).

The Confusion:

UIDynamicAnimator, UIDynamicBehavior, UIAttachmentBehavior, UIDynamicItem.....all these are causing my understanding of UIKitDynamic to overflow. I think I should be using UISnapBehavior, but I do not know how to go about it.

回答1:

As it turns out, using UIDynamicAnimator, and all other dynamic animations was not needed. All I needed was the animateWithDuration:delay:usingSpringWithDamping: initialSpringVelocity: options: animations: completion: class method. Just use it in place of any simple animateWithDuration: method, and it yields the exact behaviour i intended to achieve.

Sample code:

    [UIView animateWithDuration:0.4
                          delay:0
         usingSpringWithDamping:0.5
          initialSpringVelocity:0.5
                        options:0
                     animations:^{

                         //Animation code

                     } completion:nil];