Search code examples
iosuibuttoncore-animationuiswitch

Animate a switch using an image sequence


I would like to know how to solve a problem I'm having. I have an image sequence that basically animates a switch.

enter image description here

I'd like to implement this in iOS. How would you advise me to go for that? Maybe using UIButton? Or rather UISwitch?


Solution

  • For a rather simple solution (tap switches, no swiping possible), I would advise you to use two UIViews stacked.

    -1- At the bottom, use a UIImageView which allows you to run image animations.

    -2- At the top, use a UIControl which will capture the touché-up-inside events.

    Alternatively, you could use a UITapGestureRecognizer as a replacement for -2-. The latter option should only be considered if the resulting control will not be used for iOS < 3.2.

    As soon as your tap-recognizer (UIControl or UITapGestureRecognizer) receives the tap-event, you simply play the animation provided through your UIImageView.

    For more details on animations using UIImageView see its class reference, specifically on things like animationImages (an array of images).

    As UIImageView does not provide you with a reverse animation feature, you will have to assign the images in the reverse order before animating back to the start (that is after a user switched it on and now switches back to off).

    For a more complex solution (tap switches, swiping is possible), you may add a UISwipeGesture Recognizer to your custom control and use the status of that UIGestureRecognizer to select the currently visible image of your UIImageView.