UISwitch - 检测动画结束

Leg*_*ess 5 uiswitch ios ios8

我有一个UISwitch在里面UITableViewCell.我为切换分配了目标操作:

[switch addTarget:self action:@selector(changeSwitchColor:) forControlEvents:UIControlEventValueChanged];

- (void)changeSwitchColor:(id)sender
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

问题是changeSwitchColor:在动画完成之前调用,但我想检测动画何时完成,所以我可以在thumbTintColor不破坏动画的情况下设置属性.

我尝试使用UIView setAnimationDidStopSelector:方法检测动画:

[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是在UISwitch完成动画时不会调用此方法(我甚至不确定动画是如何在内部制作的).

我怎么能检测到完成状态UISwitch

谢谢!

Tom*_*art 7

你可以用CATransaction.setCompletionBlock(_:).

addTarget(self, action: #selector(valueChanged(sender:)), for: [.valueChanged])

@objc private func valueChanged(sender: UISwitch) {
    CATransaction.setCompletionBlock { [onChange] in
        onChange?(sender.isOn)
    }
}
Run Code Online (Sandbox Code Playgroud)

文档说,即使没有动画或动画被删除,也可以保证调用该块.它使用起来非常安全.

  • 对我不起作用:似乎直接运行而不等待切换动画完成 (6认同)