防止UIButton的setTitle:forState:动画效果

15

我正在使用 NSTimer 每秒更新一个 UIButton 的标题。

它能够工作,但是标题中的文本会自动闪烁(透明度动画到0,然后回来)。

我尝试使用 button.layer.removeAllAnimations() 但没有成功,也没有异常,因此似乎已正确链接了QuartzCore。


当前无法正常工作的警惕代码:

UIView.setAnimationsEnabled(false)
UIView.performWithoutAnimation {
    button.setTitle(time, forState: .Normal)
    button.layer.removeAllAnimations()
        }
UIView.setAnimationsEnabled(true)

你尝试过使用UIViewperformWithoutAnimation(_ actionsWithoutAnimation: () -> Void)(iOS >= 7)或者setAnimationsEnabled(_ enabled: Bool)来包装它吗? - zrzka
3个回答

50

请确保您的按钮是“自定义”按钮而不是“系统”按钮。

如果您是在Storyboard上创建的,请更改按钮类型。如果您是通过编程方式创建的,则应为:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];

4
好的!然而我不明白为什么一个系统按钮会拒绝遵循标准的UIKit指令。 - Rivera

19
我已经制作了一个Swift扩展来实现这个功能:
extension UIButton {
    func setTitleWithOutAnimation(title: String?) {
        UIView.setAnimationsEnabled(false)

        setTitle(title, forState: .Normal)

        layoutIfNeeded()
        UIView.setAnimationsEnabled(true)
    }
}

在iOS 8和9上,对于UIButtonTypeSystem类型的按钮,这对我可行。


1
最新的 Swift 发布版对我也有效。在 IB 中也使用了 UIButtonTypeSystem。谢谢! - ObjectiveTC
已在Swift 3.1上测试,仍然可用! - Paul Razvan Berg
这会禁用整个应用程序的动画,只是为了不让一个按钮动画...虽然它能够工作,但最好还是使用自定义的UIButton类型。 - Alejandro Iván

12

您可以在闭包内执行按钮更改:

UIView.performWithoutAnimation {
    //Button changes
    button.layoutIfNeeded()
}

希望这可以帮到你。


太遗憾了,结果相同。 - Rivera
另外,调用UIView.performWithoutAnimation { //Button changes }更短。但仍需要调用layoutIfNeeded()。 - varu
1
我认为这是正确的答案! - Markicevic
1
在设置setTitle调用后,只需要使用layoutIfNeeded。在UIView.performWithoutAnimation中包装它似乎在这里没有任何作用。 - stevex

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