Search code examples
ioscore-animation

animation: how to animate a view using layer?


Image showing what I would like to achieve

I want to move a view animately from a position to a new postion. If update the layer position of a view, I think the view will animately move to the new position, which is implicit animation I guess, but there's no animation, why?

- (IBAction)startAnimation:(id)sender {
    CGPoint position = self.imageView.layer.position;
    position.y += 90;
    self.imageView.layer.position = position;
}

Solution

  • Implicit animations only happen for standalone layer, not layers backing up views. You will need to explicitly animate the position. You can either do it by creating a CABasicAnimation for the position and add it to the layer or use UIView animations to animate the center property of the view.

    Creating an explicit animation

    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position"];
    move.toValue = [NSValue valueWithCGPoint:newPoint];
    move.duration = 0.3;
    [self.imageView.layer addAnimation:move forKey:@"myMoveAnimation"];
    

    Using UIView animations

    [UIView animateWithDuration:0.3 animations:^{
        self.imageView.center = newCenter;
    }];