objective c - Change NSTimer interval after a certain number of fires -
in following code, nstimer
interval set @ 1 second between each picture. goal change interval after first 2 pictures, hello.png , bye.png, 4 seconds.
- (void)viewdidload { [super viewdidload]; nsarray *imagenames = @[@"hello.png",@"bye.png",@"helloagain.png",@"bye again"]; self.images = [[nsmutablearray alloc] init]; (int = 0; < 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; [nstimer scheduledtimerwithtimeinterval:1 target:self selector:@selector(changeimage:) userinfo:nil repeats:yes]; } -(void)changeimage:(nstimer *) timer { if (counter == self.images.count - 1 ) { counter = 0; }else { counter ++; } self.animationimageview.image = self.images[counter]; }
make timer object member variable. set animation time 1 second. in callback invalidate timer , create new 1 one or 4 seconds depending on 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]; (int = 0; < 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]; }
Comments
Post a Comment