How to identify CAAnimation within the animationDidStop delegate?

后端 未结 10 2190
梦毁少年i
梦毁少年i 2020-11-28 18:26

I had a problem where I had a series of overlapping CATransition / CAAnimation sequences, all of which I needed to perform custom operations when the animations stopped, but

10条回答
  •  情歌与酒
    2020-11-28 18:53

    I can see mostly objc answers I will make one for swift 2.3 based on the best answer above.

    For a start it will be good to store all those keys on a private struct so it is type safe and changing it in the future won't bring you annoying bugs just because you forgot to change it everywhere in the code:

    private struct AnimationKeys {
        static let animationType = "animationType"
        static let volumeControl = "volumeControl"
        static let throbUp = "throbUp"
    }
    

    As you can see I have changed the names of the variables/animations so it is more clear. Now setting these keys when the animation is created.

    volumeControlAnimation.setValue(AnimationKeys.volumeControl, forKey: AnimationKeys.animationType)
    

    (...)

    throbUpAnimation.setValue(AnimationKeys.throbUp, forKey: AnimationKeys.animationType)
    

    Then finally handling the delegate for when the animation stops

    override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
        if let value = anim.valueForKey(AnimationKeys.animationType) as? String {
            if value == AnimationKeys.volumeControl {
                //Do volumeControl handling
            } else if value == AnimationKeys.throbUp {
                //Do throbUp handling
            }
        }
    }
    

提交回复
热议问题