Search code examples
iosobjective-ccore-animation

CABasicAnimation fromValue & CAKeyframeAnimation values error


I am animating a view (moveonView). Autolayout has been set for this view. When I give moveonView's 'y' position as fromValue in CABasicAnimation it's not in it's place during animation. I need to give some padding value to place it on it's correct position. Why is fromValue placing my view incorrectly? Breakpoint also reveals fromValue takes in correct 'y' value from "moveonView" but still placing the view incorrectly. What could be the reason.

CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"position.y";
animation.delegate = self;
animation.fromValue = [NSNumber numberWithFloat:_moveonView.frame.origin.y];
animation.toValue = [NSNumber numberWithFloat:self.view.frame.size.height - 100]; //[NSValue valueWithCGPoint:endPosition.origin];
animation.duration = 3;
[_moveonView.layer addAnimation:animation forKey:@"basic"];

I need to give some padding value to place it on exact position

 animation.fromValue = [NSNumber numberWithFloat:_moveonView.frame.origin.y + 50];

Solution

  • The frame's origin and the layer's position are not the same point.

    When you ask for frame.origin.y that is the y-coordinate of the top left corner of the view (on iOS), meaning that it's the same as CGRectGetMinY(frame).

    The layer's position, however, corresponds to the center of the view. So when you are animating position.y that is the same as moving the center of the view.

    You could update your from value to be using CGRectGetMidY(frame) (note the change from min to mid).

    animation.fromValue = @( CGRectGetMidY(_moveonView.frame) );