Search code examples
iosuilabelnsdatensthread

How to delay a method/animation?


so I have a simple animation in my view. It just swoops a bunch of UILabels from the top right hand side of the screen to their set coordinates. I would like a slight delay between each label though so they trickle out one by one. Right now it's just too fast:

-(void)drawLabels
{


for(int i=0; i<[self.onScreenLabels count]; i++)
{
    UILabel *label = self.onScreenLabels[i];

    int x = label.frame.origin.x;
    int y= label.frame.origin.y;

    label.center=CGPointMake(320, 0);
    [self.view addSubview:label];

    [UIView animateWithDuration:0.3 animations:^{
        label.center=CGPointMake(x, y);


    }];

    NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.5 ];
    [NSThread sleepUntilDate:future];



}

}

I would like to have a delay after drawing each label on screen, you an see above I have tried to use NSDate and NSThread however it doesn't seem to make any difference. Any ideas? Thanks


Solution

  • Another approach using animateWithDuration:delay:

    CGFloat delay = 0.0f;
    
    for(int i=0; i<[self.onScreenLabels count]; i++)
    {
        UILabel *label = self.onScreenLabels[i];
    
        int x = label.frame.origin.x;
        int y = label.frame.origin.y;
    
        label.center=CGPointMake(320, 0);
        [self.view addSubview:label];
    
        [UIView animateWithDuration:0.3 delay:delay options:0 animations:^{
    
            label.center=CGPointMake(x, y);
    
        } completion:^(BOOL finished){
    
        }];
    
        delay += 0.5f;                  // add 1/2 second delay to each label (0, 0.5, 1.0, 1.5)
    
    }