iphone 开发 : how to create an animation by using NSTimer

标签 iphone objective-c ios animation nstimer

在我的应用程序中,我在 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 正是这样做的,让您的动画像黄油一样运行。

文档: 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];
}

关于iphone 开发 : how to create an animation by using NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12139675/

相关文章:

iphone - AudioServicesPlaySystemSound 和主线程

objective-c - 检查一个 NSArray 的内容是否都在另一个数组中

ios - facebook SDK 中缺少 FBSessionStateOpen [Firebase 引用.,Swift]

iphone - iOS7屏幕截图有白噪声

iphone - CL位置距位置的距离

ios - 设置内容偏移时iOS7中的搜索栏半隐藏

ios - 在 UIGestureRecognizer 中双击

ios - Swift View 模型 : function vs setter with side effect

iphone - 使用适用于 iOS 的 Facebook SDK 帮助访问粉丝页面

iphone - UITableView懒加载优化