在我的应用程序中,我在 viewWillAppear 中有这段代码。它只是将随机对象从屏幕顶部动画化到底部。问题是我需要检测碰撞,到目前为止我学到的是不可能随时检索动画的坐标。那么如何使用 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];
}];
}
最佳答案
我会放弃 NSTimer
而使用 CADisplayLink
来向您的目标发送消息。 NSTimer
可能会导致动画断断续续,因为它与设备的屏幕刷新率不同步。 CADisplayLink
正是这样做的,让您的动画像黄油一样运行。
最终,使用 CADisplayLink
看起来像这样:
- (id) init {
// ...
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
// ...
}
- (void) update {
[myView updatePositionOrSomethingElse];
}
关于iphone 开发 : how to create an animation by using NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139675/