I have an UISwitch
which is inside of a UITableViewCell
. I have a target action assigned to switch:
[switch addTarget:self action:@selector(changeSwitchColor:) forControlEvents:UIControlEventValueChanged];
- (void)changeSwitchColor:(id)sender
{
...
}
The problem is that the changeSwitchColor:
is called before the animation is finished, yet I want to detect when animation has finished, so I can set the thumbTintColor
property without breaking the animation.
My attempt to detect the animation by using UIView
setAnimationDidStopSelector:
method:
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
...
}
But this method is not called on UISwitch
finishing the animation (I'm not even sure how the animation is made internally).
How could I detect the finishing state of UISwitch
?
Thanks!
You can use CATransaction.setCompletionBlock(_:)
.
addTarget(self, action: #selector(valueChanged(sender:)), for: [.valueChanged])
@objc private func valueChanged(sender: UISwitch) {
CATransaction.setCompletionBlock { [onChange] in
onChange?(sender.isOn)
}
}
The documentation says the block is guaranteed to be called even if there are no animations or the animation was removed. It makes it very safe to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With