0

I want to animate the 'on' color of a UISwitch AND keep it interactable, with no compromise to it's on / off animation. Here's what I tried:

  1. UIView's animate with duration method doesn't work because well...it shouldn't, 'onTintColor' isn't listed as an animatable property of UIView. Fine.

    mySwitch.onTintColor = UIColor.green
    
    UIView.animate(withDuration: 10) {
        mySwitch.onTintColor = UIColor.red
    }
    
  2. Next. UIView's transition with view method gives sort of the correct visual behaviour however when interacting with the switch the default on / off animation is compromised (see GIF).

    UIView.transition(with: mySwitch, duration: 10, options: [.transitionCrossDissolve, .allowUserInteraction], animations: { 
        mySwitch.onTintColor = UIColor.red
    }) { completed in
    }
    
  3. CATransition gives the same behaviour as no. 2 (see GIF).

    var transition = CATransition()
    transition.type = kCATransitionFade
    transition.duration = 10
    mySwitch.layer.add(transition, forKey: kCATransition)
    mySwitch.onTintColor = UIColor.red
    

via GIPHY

Anyone have any ideas how I can animate the 'onTintColor' without affecting the default on / off animation?

Is the only way of doing this properly going to be to create a custom switch?

Andrew Morris
  • 254
  • 4
  • 11

1 Answers1

3

By default user interaction is disabled during animations. Try using the longer form of UIView animations,

animate(withDuration:delay:options:animations:completion:), and pass in options of .allowUserInteraction

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • thanks for that suggestion. Passing that option to transition with view does what it says which is great but it also effects the switch's default on / off animation. Please see my edit and linked GIF :) – Andrew Morris Jul 10 '17 at 09:02