简体   繁体   English

NSTimer更快地移动UIImageView

[英]NSTimer move UIImageView faster

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. 我使用NSTimer每1秒移动一次UIImageView,我想将每2秒的时间从1减少到0.5,因为结果是图像在视图内的移动速度更快。 Any ideas will be very help full. 任何想法都会非常有帮助。

This is the timer that i use for moving the UIImageView 这是我用于移动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 我相信我做错了

Are you wanting to move the image every 2 seconds, or make it move increasingly faster? 您要每2秒移动一次图像,还是使其移动得更快? It won't move faster, if you only move it every 2 seconds. 如果仅每2秒移动一次,它将不会更快。

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. 您可以阅读NSTimer的文档,但要摆脱一些麻烦,下面是一些如何使用NSTimer的示例。

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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM