My Silver Challenge Solution


#1

It was a little hard to understand how to chain animations, I thought I could use animateKeyframesWithDuration: but it didn’t work like I was expecting

First I wrote a new method to animate labels, I did this because the animation is the same for the question label and the answer label:

- (void)animateLabel:(UILabel *)label withString:(NSString *)string
{
    // To maintain the original position
    CGRect currentRect = label.frame;
    
    // lefttRect has the far left poisition in the X-Axis
    CGRect leftRect = currentRect;
    leftRect.origin.x = 0 - label.frame.size.width;
    
    // rightRect has the far right position in the X-Axis
    CGRect rightRect = currentRect;
    rightRect.origin.x = [[UIScreen mainScreen] bounds].size.width;
    
    // The first animation moves the label to right
    // and the second one changes the text moves the label to the far left and
    // then moves the label to the original position
    // Both change the alpha values of the labels.
    [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         label.frame = rightRect;
                         label.alpha = 0;
                         
                     } completion:^(BOOL finished){
                         label.text = string;
                         label.frame = leftRect;
                         [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseOut
                                          animations:^{
                                              label.frame = currentRect;
                                              label.alpha = 1;
                                          } completion:NULL
                          ];
                     }];
}

Then I did a little modifications to the action methods to call animateLabel:withString:

[code]- (IBAction)showQuestionButtonPressed:(UIButton *)sender
{
// Step to the next question
self.currentQuestionIndex++;

// Am I pas the last question?
if (self.currentQuestionIndex == [self.questions count]) {

    // Go back to the first question
    self.currentQuestionIndex = 0;
}

// Get the string at the index in the questions array
NSString *question = self.questions[self.currentQuestionIndex];

// Display the string in the question label
[self animateLabel:self.questionLabel withString];

// Don't do anything if the text is ???
if (![self.answerLabel.text isEqualToString:@"???"]) {
    [self animateLabel:self.answerLabel withString:@"???"];
}

}

  • (IBAction)showAnswerButtonPressed:(UIButton *)sender
    {
    // What is the answer to the current question?
    NSString *answer = self.answers[self.currentQuestionIndex];

    // Display it in the answer label
    [self animateLabel:self.answerLabel withString:answer];
    }
    [/code]

Hope it’s ok!