3

Basically I am trying to implement an animation that will replace a label's text for a few seconds before returning to the original text. I have managed to get the label to change text and fade out after 3 seconds, however I can't figure out how to return the text to the original state after the animation is complete.

Here is what I currently have:

    @IBAction func fade() {
    userMessageLabel.alpha = 100
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(3)
    userMessageLabel.text = "Name is not valid!"
    userMessageLabel.alpha = 0
    UIView.commitAnimations()
}

I need the text label to return to "Please enter your first name"

Any help would be much appreciated.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
user3746428
  • 10,497
  • 19
  • 72
  • 129

3 Answers3

5

I solved this problem by using a delay:

userMessageLabel.text = "Name is not valid!" 
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
  userMessageLabel.text = "Please enter your first name"
}

My solution includes a slight simplification of the delay from this answer

You seem to already know how to animate text to fade out or in. If desired, add animation code into the asyncAfter delay function

Community
  • 1
  • 1
PlateReverb
  • 594
  • 1
  • 6
  • 21
0

Using the following class method on UIView would probably be the best way. Once the animation finishes - if you provide a completion block that code will get executed.

In your example you could make the completion block, reset the text label to your desired value.

class func animateWithDuration(_duration: NSTimeInterval,
                animations animations: (() -> Void)!,
                completion completion: ((Bool) -> Void)!)

Something along these lines would achieve the desired effect. Within the completion block, you could have another animation.

UIView.animateWithDuration(3.0, animations: { 
       userMessageLabel.text = "Name is not valid!"
       userMessageLabel.alpha = 0.0
    }, completion: {
       userMessageLabel.alpha = 1.0  
       userMessageLabel.text = "Please enter your first name" 
   })
kurtn718
  • 741
  • 6
  • 5
0

I tested this with Swift3 from this and it works perfectly!

Objective-C

[UIView transitionWithView:self.label 
                  duration:0.25f 
                   options:UIViewAnimationOptionTransitionCrossDissolve 
                animations:^{

    self.label.text = rand() % 2 ? @"Nice nice!" : @"Well done!";

  } completion:nil];

Swift 3

UIView.transition(with: label,
              duration: 0.25,
               options: .transitionCrossDissolve,
            animations: { [weak self] in
                self?.label.text = (rand() % 2 == 0) ? "One" : "Two"
         }, completion: nil)
S At
  • 143
  • 2
  • 9