iphone开发:如何使用NSTimer创buildanimation

在我的应用程序中,我在viewWillAppear中有这个代码。 它只是将从屏幕顶部到底部的随机对象animation化。 问题是我需要检测碰撞,到目前为止我所学到的是不可能在任何时候检索animation的坐标。 那我该如何使用NSTimer来实现呢? 或者我应该使用NSTimer? 我无法弄清楚。 任何线索将不胜感激。

-(void)viewWillAppear:(BOOL)animated { for (int i = 0; i < 100; i++) { p = arc4random_uniform(320)%4+1; CGRect startFrame = CGRectMake(p*50, -50, 50, 50); CGRect endFrame = CGRectMake(p*50, CGRectGetHeight(self.view.bounds) + 50, 50, 50); animatedView = [[UIView alloc] initWithFrame:startFrame]; animatedView.backgroundColor = [UIColor redColor]; [self.view addSubview:animatedView]; [UIView animateWithDuration:2.f delay:i * 0.5f options:UIViewAnimationCurveLinear animations:^{ animatedView.frame = endFrame; } completion:^(BOOL finished) { [animatedView removeFromSuperview]; }]; } 

您的声明:

是否可以随时检索animation的坐标?

似乎不正确你检查了吗?

它看起来像你可以使用CALayer的presentationLayer属性来提取animation过程中的坐标信息:

 CGRect movingFrame = [[yourView.layer presentationLayer] frame]; 

如果在animation期间发生碰撞,我将使用这些信息来检查时间。 所以我会使用定时器来检查碰撞状态而不是animation的意见。

我会抛弃CADisplayLink发送消息到您的目标。 NSTimer可能导致口吃animation,因为它不与设备的屏幕刷新率同步。 CADisplayLink正是这样做,并使您的animation像黄油一样运行。

文档: http : //developer.apple.com/library/ios/#documentation/QuartzCore/Reference/CADisplayLink_ClassRef/Reference/Reference.html

最终,使用CADisplayLink看起来像这样:

 - (id) init { // ... CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)]; [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; // ... } - (void) update { [myView updatePositionOrSomethingElse]; } 

你可以让你的对象以小增量animation(在一个循环中)。 每当你完成你的animation,你可以得到坐标。

我想你可以在一个for循环中使用beginAnimations – commitAnimations语法,它可以用于例如。 直到10,所以在每个循环之后你可以检查碰撞

 CGRect incrementedViewFrame; for(int i = 0; i < 10; ++i) { incrementedViewFrame = CGRectMake(/*calculate the coords here*/); if(collision) { //do stuff } else { //do an other animation cycle [UIView beginAnimations:nil context:NULL]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:0.1f]; [[self viewToAnimate]setFrame:incrementedViewFrame]; [UIView commitAnimations]; } } 

我希望有帮助!