简体   繁体   中英

UIKit Dynamics doesn't allow me to animate a UIView's centre

I have a UIView which is attached to a UICollisionBehavior . I'm trying to animate its center when a new location is tapped on the screen, but it appears using this block of code is not the way to do it:

    [UIView animateWithDuration:0.7f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         [self.mainCharacter setCenter:location];
                     }
                     completion:nil];

Can anyone suggest a more UIKitDynamics friendly way of doing this?

Thanks.

UPDATE

So the first part of my question was similar to the one posted and a possible duplicate, however, although technically it solved the issue in the first part of this question, it does seem to interfere with how collision testing in UICollisionBehavior .

The second part of this question was to ask if there was a better way of doing this. I assumed it would be possible to accelerate a UIDynamicItem at a speed over a given time using UIPushBehavior but it seems to be constant.

Can anyone recommend how to use a UIPushBehavior to do the above?

In UIKit Dynamics, when you want to animate changing the center, you'd add a UISnapBehavior to your UIDynamicAnimator (removing any prior snap behavior first). For example, create a property for the UISnapBehavior , and then your tap gesture recognizer can snap it to that point (honoring your UICollisionBehavior ), like so:

- (void)handleTap:(UITapGestureRecognizer *)gesture
{
    if (self.snap)
        [self.animator removeBehavior:self.snap];

    CGPoint point = [gesture locationInView:gesture.view];
    UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:self.viewToAnimate snapToPoint:point];
    [self.animator addBehavior:snap];

    self.snap = snap;
}

You can control the "bounciness" by adjusting the damping property of the UISnapBehavior . If you don't like it rotating the view as it's snapping, you can also add a UIDynamicItemBehavior with allowsRotation set to NO .

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