简体   繁体   中英

Swift: how to finish a UIView draw animation before changing a label

I have a little problem regarding the timing of an animation.

The sequence should be:

  1. Button is pressed
  2. Animation is displayed
  3. Label is changed

In reality the sequence is:

  1. Button is pressed
  2. Label is changed
  3. Animation is displayed

Here is the code of the main VC:

import Foundation
import UIKit

class MainVC: UIViewController {

  var counter: Int = 0

  @IBOutlet weak var counterLabel: UILabel!
  
  @IBOutlet weak var nextButton: UIButton!

  @IBOutlet weak var animationView: AnimationView!

  @IBAction func nextButtonPressed(_ sender: UIButton) {
     counter += 1
     animationView.progress = 1
     //this view draws a progress bar and animates it from 0 to 100% via CABasicAnimation. 
     counterLabel.text = "\(counter)"
     animationView.progress = 0 
     //the progress bar is reset
  }

  override func viewDidLoad() {
     super.viewDidLoad()
     nextButton.setTitle("Next")
     counterLabel.text = "\(counter)"
  }

}

I've experimented with the dispatch queue, but I just can't get it to work right. Any ideas on how to solve this?

You don't show enough of your code for us to be able to help you specifically.

In general, you would set some object to be the delegate of your CAAnimation, and implement the method func animationDidStop(_ anim: CAAnimation, finished flag: Bool) .

In that method you'd then change the label text (assuming finished == true .)

I don't really like the delegate pattern for animations. If you have multiple animations it can be painful to handle custom completion code for each one. What I've done is use the fact that you can attach objects to CAAnimation objects, and attach a closure to the animation. I then set the view controller to be the delegate, and in the view controller's animationDidStop() , I look for a closure attached to the animation, and execute it if there is one.

Edit:

See this article for a discussion on using key-value coding to attach objects to CAAnimation and CALayer objects:

Core Animation Key-value coding extensions

It's old, and written using Objective-C, but the concepts are the same in Swift, and very useful. For a more general discussion on key-value coding, which is updated for Swift, see this article: https://developer.apple.com/documentation/objectivec/nsobject/nskeyvaluecoding

(The two functions you need to know in Swift are setValue(_:forKeyPath:) and value(forKey:) .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM