Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISwitch - detecting end of animation

Tags:

ios

ios8

uiswitch

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!

like image 204
Legoless Avatar asked Oct 02 '14 07:10

Legoless


1 Answers

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.

like image 90
Tomáš Linhart Avatar answered Sep 28 '22 09:09

Tomáš Linhart