UISwitch - 检测动画结束

6

我有一个UISwitch,它在UITableViewCell中。我已经将目标操作分配给开关:

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

- (void)changeSwitchColor:(id)sender
{
    ...
}

问题在于在动画完成之前调用了changeSwitchColor:方法,但我想检测动画何时结束,这样我就可以设置thumbTintColor属性而不会中断动画。
我尝试使用UIViewsetAnimationDidStopSelector:方法来检测动画:
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    ...
}

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

我该如何检测 UISwitch 的完成状态?

谢谢!


你可以从其他stackoverflow答案链接中找到你的答案:https://dev59.com/g2Ik5IYBdhLWcg3wDaUW - Nimisha Patel
那个问题会如何回答我的疑问呢? - Legoless
UISwitch 不是一个好的类。它很难被重写或自定义。我认为你应该重写 UIControl 并创建自己的开关。 - Tony
我真的很想避免自己制作开关,当然我知道 UIControl - Legoless
2个回答

9
您可以使用 CATransaction.setCompletionBlock(_:)
addTarget(self, action: #selector(valueChanged(sender:)), for: [.valueChanged])

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

文档称即使没有动画或动画已被移除,该块也保证会被调用。这使得它非常安全易用。

6
对我没用:似乎只是直接运行,而不等待开关动画完成。 - xaphod
也许这种行为在旧版的iOS中有所不同? - Tieme

1

Tomáš使用Swift 4进行回答:

settingsSwitch.addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged)

@objc func valueChanged(_ sender: UISwitch) {
    CATransaction.setCompletionBlock {
        //... animation just finished
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接