0
votes

I use an NSTimer to move a UIImageView every 1 second, I want to decrease the time every 2 seconds from 1 to 0.5 as result the image will move faster inside the view. Any ideas will be very help full.

This is the timer that i use for moving the UIImageView

float obstaclesSpeed = 1.0;

 movementTimer = [NSTimer scheduledTimerWithTimeInterval:obstaclesSpeed target:self selector:@selector(updateSpeed) userInfo:nil repeats:YES];

This is my code

-(void)updateSpeed {

    obstaclesSpeed = obstaclesSpeed / 2;

    [self startMoveObstacles];

}

I believe something I do wrong

1
Every 2 seconds, currentTime= currentTime/2. Is it right? - nmh
Hi nmh the NSLog shows that the time is divide by every sec but the UIImageView is not moving faster - gkonstandas
you are changing the obstaclesSpeed variable in your class the NSTimer object has no knowledge of it.. you need to create a new, non repeating timer with lesser time interval on every iteration... - Swapnil Luktuke

1 Answers

0
votes

Are you wanting to move the image every 2 seconds, or make it move increasingly faster? It won't move faster, if you only move it every 2 seconds.

You can read the docs for NSTimer, but to take some of the headache out of it, here's some examples of how to use NSTimer for this.

If you're wanting to move it every two seconds, you can do the following.

- (void) startTimer {
    [_myTimer invalidate];
    _myTimer = nil;
    _myTimer = [NSTimer timerWithTimeInterval:2. target:self selector:@selector(respondToTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_myTimer forMode:NSRunLoopCommonModes];
}

- (void)respondToTimer:(NSTimer*)timer {
    //Code to move your UIImageView
}

If you're wanting to move it increasingly faster, you can do the following.

- (void) startTimer {
    [_myTimer invalidate];
    _myTimer = nil;
    _myTimer = [NSTimer timerWithTimeInterval:_timeInterval target:self selector:@selector(respondToTimer:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:_myTimer forMode:NSRunLoopCommonModes];
}

- (void)respondToTimer:(NSTimer*)timer {
    //Code to move your UIImageView
    _numberOfMoves++;
    if (_numberOfMoves < MAX_MOVES) {
        _timeInterval /= 2;
        [self startTimer];
    }
}