Change NSTimer interval after a certain number of fires

前端 未结 3 1386
死守一世寂寞
死守一世寂寞 2021-01-26 14:48

In the following code, the NSTimer interval is set at 1 second between each picture. My goal is to change the interval after the first two pictures, hello.png and b

3条回答
  •  悲哀的现实
    2021-01-26 15:05

    Make the timer object a member variable. Initially set animation time as 1 second. In the callback invalidate the timer and create a new one with 1 or 4 seconds depending on the counter.

    @interface ViewController ()
    @property (strong,nonatomic) NSMutableArray *images;
    @property (strong,nonatomic) UIImageView *animationImageView;
    {
        NSTimer *_timer;
    }
    @end
    
    @implementation ViewController {
        NSInteger counter;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSArray *imageNames = @[@"hello.png",@"bye.png",@"helloagain.png",@"bye again"];
    
        self.images = [[NSMutableArray alloc] init];
        for (int i = 0; i < imageNames.count; i++) {
            [self.images addObject:[UIImage imageNamed:[imageNames objectAtIndex:i]]];
        }
    
        self.animationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 95, 86, 90)];
        self.animationImageView.image = self.images[0];
        [self.view addSubview:self.animationImageView];
        self.animationImageView.userInteractionEnabled = TRUE;
    
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bannerTapped:)];
        singleTap.numberOfTapsRequired = 1;
        singleTap.numberOfTouchesRequired = 1;
        [self.animationImageView addGestureRecognizer:singleTap];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeImage:) userInfo:nil repeats:YES];
    }
    
    
    -(void)changeImage:(NSTimer *) timer {
         [_timer invalidate];
        if (counter == self.images.count - 1 ) {
            counter = 0;
        }else {
            counter ++;
        }
        if(counter == 0 || counter == 1)
        {
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeImage:) userInfo:nil repeats:YES];
        }
        else if(counter == 2 || counter == 3)
        {
            _timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(changeImage:) userInfo:nil repeats:YES];
        }
        self.animationImageView.image = self.images[counter];
    }
    

提交回复
热议问题