1

我只想用这个函数为我的 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 进入奇怪的位置......

4

2 回答 2

17

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

无论如何,您正在对位置进行相对动画,因此如果您跳过 and 而是使用该属性(具有相对变化)会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"];
于 2012-10-23T13:48:59.900 回答
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
                 }];
于 2012-10-23T13:50:37.903 回答