0

I have a method to fade in, then fade out a button label (shown below):

    -(void)fade:(NSString *)text
 {

     NSLog(@"Starting Fade In for symbol %@",text);
     [self.symbolButton setAlpha:0.0f];
     [self.symbolButton setTitle:text forState:UIControlStateNormal];
     [UIView animateWithDuration:2 animations:^{
         [self.symbolButton setAlpha:1.0f];

     } completion:^(BOOL finished) {

     NSLog(@"Starting Fade Out for symbol %@",text);
    [UIView animateWithDuration:2 animations:^{
    [self.symbolButton setAlpha:0.0f];
    } completion:nil];
    }];
 }

This works as intended. However, rather than a single string, I want to cycle through the contents of an array (eg. fade-in "A", fade-out "A", fade-in "B", fade-out "B".....).

In the above code, the completion block waits for the fade-in to finish before starting the fade-out (good). However, if I try and process an array using a for loop (modify the method to accept array and nest actions in a for loop that iterates the array), the loop cycles immediately rather than waiting for first character to complete.

Is there a way to use a completion block in the second animation action to pause processing of the loop - or am I going about this in the wrong way?

user1676300
  • 135
  • 7
  • 1
    recursion can be a solution, but in mordern programming paradigm, it's bad to use recursion. call the same function in the completion. – Ratul Sharker Jan 24 '16 at 17:05

1 Answers1

0

You may try this. I didn't test it but the idea should work

NSArray<UIButton*>* arrButtons;
NSString* text;

for (int i = 0 ; i < arrButtons.count; i++) {
    UIButton* b = arrButtons[i];
    b.alpha = 0.0f;
    [b setTitle:text forState:UIControlStateNormal];

    [UIView animateKeyframesWithDuration:2 delay:4*i options:0 animations:^{

        b.alpha = 1.0f;

    } completion:^(BOOL finished) {

        NSLog(@"Starting Fade Out for symbol %@",text);

        [UIView animateWithDuration:2 animations:^{
            b.alpha = 0.0f;
        } completion:nil];

    }];

}
Yedidya Reiss
  • 5,316
  • 2
  • 17
  • 19