1

我得到了一个数组“coordList”,其中的数组保存了 xy 坐标。
我想沿着这些坐标移动视图。

如果您有更好的方法来做到这一点,请告诉我该怎么做。

我这样做的方式有一个大问题。它直接跳到最后一个动画,我知道为什么但不知道如何修复它。

我的代码:

count = 1;
for(NSArray *array in coordList) {  
    [UIView animteWithDuration:1 animations:^(void){
        CGRect r = [[self.subviews lastObject] frame];  
        r.origin.x = 103*[coordList[count][0]integerValue];  
        r.origin.y = 103*[coordList[count][1]integerValue];  
        [[self.subviews lastObject] setFrame:r];  
        count++;
        [UIView commitAnimations];
    }
}

对不起,我的英语不好 :)

4

2 回答 2

0

正在发生的事情是您正在为同一个视图提交多个动画,因此每次为该视图提交新动画时,它都会覆盖其他现有动画。

您需要将动画设置为一个接一个地触发。所以一个简单的 for 循环不会那么好。

我会推荐一个这样的递归例程:

//set a property to keep current count
@property (nonatomic, asssign) NSInteger currentFrame;

//initialize it to 0 on init
currentFrame = 0;

//call this once when ready to animate
[self animationWithCurrentFrame];


//it will call this routine once for each array.
- (void)animationWithCurrentFrame {
    __block NSArray *array = [coordList objectAtIndex:currentFrame];
    [UIView animateWithDuration:2.0
                     animations:^{
                         CGRect r = [[self.subviews lastObject] frame];
                         r.origin.x = 103*[array[0]integerValue];
                         r.origin.y = 103*[array[1]integerValue];
                         [[self.subviews lastObject] setFrame:r];  
                     }
                     completion:^(BOOL finished){
                         currentFrame++;
                         if (currentFrame < [coordList count]) {
                             [self animationWithCurrentFrame];
                         }

                     }];
    }
于 2013-09-07T19:45:21.077 回答
0

这是一个理想的应用程序CAKeyFrameAnimation。而且你不做一堆动画,而是定义一个路径,然后执行一个动画,将该路径指定为“位置”:

UIView *viewToAnimate = [self.subviews lastObject];

// create UIBezierPath for your `coordList` array

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(103*[coordList[0][0]integerValue], 103*[coordList[0][1]integerValue])];
for (NSInteger i = 1; i < [coordList count]; i++)
{
    [path moveToPoint:CGPointMake(103*[coordList[i][0]integerValue], 103*[coordList[i][1]integerValue])];
}

// now create animation

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.path = [path CGPath];
animation.duration = 2.0;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[viewToAnimate.layer addAnimation:animation forKey:@"position"];

为此,您必须将 QuartzCore 框架添加到您的项目中,并在 .m 文件的顶部导入适当的头文件:

#import <QuartzCore/QuartzCore.h>

有关更多信息,请参阅 核心动画编程指南中的关键帧动画以更改图层属性。

如果您使用自动布局,请不要忘记在完成后重置此视图的约束。

于 2013-09-07T21:57:10.243 回答