0
votes

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?

1

1 Answers

3
votes

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