Search code examples
objective-ccocoacore-animation

CABasicAnimation not having any effect


I'm having a very simple issue, and I'm pulling out my hair over it. I'm trying to animate the moving of an NSButton. Now, I am aware of the almost overly simple:

[[button animator] setFrame:newCGRect];

However, I'd like to increase the time it takes for the button to travel. So, I looked into the slightly more complex CABasicAnimation. I think I'm doing everything correctly, but the NSButton isn't moving at all.

CGPoint center = CGPointMake(10, 20);

CALayer *layer = button.layer;

layer.position = CGPointMake(button.frame.size.width / 2, button.frame.size.height / 2);

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue = [layer valueForKey:@"position"];
[animation setToValue:[NSValue valueWithPoint:center]];
[animation setFillMode:kCAFillModeForwards];
[animation setRemovedOnCompletion:NO];
[animation setDuration:3.0];

[layer addAnimation:animation forKey:@"position"];

Here, button is the NSButton. I'm setting the position of layer to the center of the button, because I think that "position" has to refer to the center. Then, all I'm doing is moving (supposedly) the button to center, in an animation that is 3 seconds long. I add the animation to the layer, and then, nothing happens.

Now, does anybody know what I'm doing wrong? Or, on a side note, is there anyway to use the animator property and set the length of the animation?


Solution

  • It turns out my original code was overkill, and Jason Harwig's answer below was more accurate. The only problem was his did not animate with the given duration when animating an NSView subclass (in this case, an NSButton). To remedy to this, here is the following code, that animates with the given duration:

    [NSAnimationContext beginGrouping];
    [[NSAnimationContext currentContext] setDuration:8];
    [[button animator] setFrame:newRect];  
    [NSAnimationContext endGrouping];