Repeat delay in UIView animation loop?

I am trying to make a custom animation in the opacity of the view as follows:

  • Delay for 5 seconds; (The view will be opaque for 5 seconds).
  • Animation from opacity value from 1 to 0;
  • Delay for 5 seconds; (The view will remain transparent for 5 seconds).
  • Animation from opacity value from 0 to 1;

I want to repeat steps 1 to 4 endlessly: 1, 2, 3, 4, 1, 2, 3, 4, .....

Here is what I tried:

[UIView animateWithDuration:1 delay:5 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveEaseInOut animations:^{ self.imageView.layer.opacity = 0; } completion:nil ]; 

But the delay appeared only once in the beginning that I ended up:

1, 2, 4, 2, 4, 2, 4, .....

+4
source share
2 answers

I had the same problem. I decided this way using NSTimer

 [NSTimer scheduledTimerWithTimeInterval: 2 target: self selector:@selector(moveImage: ) userInfo: nil repeats:YES]; } -(void) moveImage: (NSTimer*)timer { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:2]; 
+5
source

@ user1980004 Thanks for the NSTimer tip. I will just post the full working code for my question:

 // interface @property (strong, nonatomic) IBOutlet UIImageView *imageView; @property (strong, nonatomic) NSTimer *animationTimer; -(void) viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; [self glowAnimation]; // Timer fires after a delay, so I need to fire animation for the first time // The interval value is determined by the sum of delay and duration for both the forward and reverse animation in glowAnimation function; self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:12 target:self selector:@selector(glowAnimation) userInfo:nil repeats:YES]; } -(void) viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; if (self.animationTimer){ [self.animationTimer invalidate]; // Cancel the timer schedule self.animationTimer = nil; } } -(void) glowAnimation{ // Forward and reverse animation are chained with delay in each. [UIView animateWithDuration:1 delay:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.imageView.layer.opacity = 0; } completion:^(BOOL finished){ [UIView animateWithDuration:1 delay:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.imageView.layer.opacity = 1; } completion:nil ]; } ]; } 

All together the animation sequence 1, 2, 3, 4, 1, 2, 3, 4 in question can be achieved.

+1
source

Source: https://habr.com/ru/post/1484575/


All Articles