Is this a good way to use position to move a CALayer permanently? Do I really need a to and from value animation?
serveBlock2 = [CALayer layer];
serveBlock2.zPosition = 1;
[serveBlock2 setFrame:CGRectMake(screenBounds.size.height/2, 0, screenBounds.size.height/2, screenBounds.size.width)];
[serveBlock2 setOpacity:0.0f];
[serveBlock2 setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.8f].CGColor];
[self.view.layer addSublayer:serveBlock2];
CABasicAnimation *updateCurrentServe2 = [CABasicAnimation animationWithKeyPath:@"position.y"];
serveBlock2.position = CGPointMake((screenBounds.size.height/4)*3, -screenBounds.size.width/2);
[updateCurrentServe2 setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.8 :-0.8 :1.0 :1.0]];
[updateCurrentServe2 setDuration:1.5];
[serveBlock2 addAnimation:updateCurrentServe2 forKey:@"serveBlock2 updateCurrentServe2"];
You have two questions there and I will answer them in the opposite order:
No, you don't need that.
CABasicAnimation has three properties that go together define how the interpolation is done, these are fromValue
, byValue
and toValue
. They can be combined in many different ways which is listed under the "Setting Interpolation Values" section in the CABasicAnimation documentation. The very last listed combination is:
- All properties are
nil
. Interpolates between the previous value ofkeyPath
in the target layer’s presentation layer and the current value ofkeyPath
in the target layer’s presentation layer.
So what you are doing and the results you are seeing is documented behavior and works.
This is a very opinionated question and I can only give you my personal opinion and try and explain my reasoning.
I personally don't like it because it is less explicit and you would need to have read this special case in the documentation to know how it works. As you saw in the comment on your question I wasn't even sure how this worked when I first saw it and I consider myself very familiar with Core Animation and have read the documentation many times.
It all should come down to what you and your team thinks is most readable and clear.
Personally I prefer to explicitly set the new model value and then only specify the fromValue
, i.e. this case:
fromValue
is non-nil
. Interpolates between `fromValue and the current presentation value of the property.