UISwitch - end animation detection
I have UISwitch
one that is inside UITableViewCell
. I have a target action assigned to toggle:
[switch addTarget:self action:@selector(changeSwitchColor:) forControlEvents:UIControlEventValueChanged];
- (void)changeSwitchColor:(id)sender
{
...
}
The problem is what changeSwitchColor:
is called before the animation finishes, but I want to detect when the animation is finished, so I can set the property thumbTintColor
without breaking the animation.
My attempt at detecting animation using the method UIView
setAnimationDidStopSelector:
:
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
...
}
But this method is not called when UISwitch
the animation ends (I'm not even sure how the animation is done internally).
How to determine the completion status UISwitch
?
Thank!
source to share
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 that the block is guaranteed to be called even if there is no animation or the animation has been removed. This makes it very safe to use.
source to share