CABasicAnimation Position.Y

时间:2012-10-15 12:03:16

标签: iphone objective-c

我只想使用此功能为我的UIButton的位置设置动画:

CABasicAnimation *moveUp;
    moveUp          = [CABasicAnimation animationWithKeyPath:@"position.y"];
    moveUp.fromValue = [NSNumber numberWithFloat:self.retestBTN.frame.origin.y];
    moveUp.toValue  = [NSNumber numberWithFloat:self.retestBTN.frame.origin.y - 50];
    moveUp.duration = 1.0;
    moveUp.removedOnCompletion = NO;
    moveUp.fillMode = kCAFillModeBoth;
    moveUp.delegate = self;
    [[retestBTN layer] addAnimation:moveUp forKey:@"y"];

然后我希望稍后使用该功能将其设置为动画:

CABasicAnimation *moveDown;
moveDown            = [CABasicAnimation animationWithKeyPath:@"position.y"];
moveDown.fromValue  = [NSNumber numberWithFloat:self.retestBTN.frame.origin.y];
moveDown.toValue    = [NSNumber numberWithFloat:self.retestBTN.frame.origin.y + 50];
moveDown.duration   = 1.0;
moveDown.removedOnCompletion = NO;
moveDown.fillMode   = kCAFillModeForwards;
[[retestBTN layer] addAnimation:moveDown forKey:@"y"];

但是这不能正常运行,我的UIButton走向了奇怪的位置......

2 个答案:

答案 0 :(得分:13)

您面临的问题是位置与原点不同。

无论如何,你正在做位置的相对动画,所以如果你跳过toValuefromValue而不是使用byValue属性(相对更改)会更容易。你的代码看起来像这样:

CABasicAnimation *moveUp;
moveUp          = [CABasicAnimation animationWithKeyPath:@"position.y"];      
moveUp.byValue  = @(-50.0f); // or [NSNumber numberWithFloat:-50.0f] if you really need to
moveUp.duration = 1.0;
moveUp.removedOnCompletion = NO;
moveUp.fillMode = kCAFillModeBoth;
moveUp.delegate = self;
[[retestBTN layer] addAnimation:moveUp forKey:@"y"];

CABasicAnimation *moveDown;
moveDown            = [CABasicAnimation animationWithKeyPath:@"position.y"];
moveDown.byValue    = @(50.0f); // or [NSNumber numberWithFloat:50.0f] if you really need to
moveDown.duration   = 1.0;
moveDown.removedOnCompletion = NO;
moveDown.fillMode   = kCAFillModeForwards;
[[retestBTN layer] addAnimation:moveDown forKey:@"y"];

答案 1 :(得分:3)

通过使用CAAnimation,您只能为图层设置动画。实际上,您实际上并没有更改对象的modelLayer,而只更改presentationLayer,因为您只创建动画,而实际上从未更改图层的position属性。这意味着按钮实际上不会移动,只是在屏幕上绘制的位置移动。

如果您的按钮是UIButton,那么它仍将接收视图所在的触摸,而不是图层所在的位置。您可以使用UIKit更轻松地为任何视图制作动画:

[UIView animateWithDuration:1.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     CGRect frame = self.retestBTN.frame;
                     frame.origin.y -= 50;
                     self.retestBTN.frame = frame;
                 }
                 completion:^(BOOL finished){
                     //callback code goes here
                 }];