防止UIButton的setTitle:forState:动画

Riv*_*era 10 animation objective-c uibutton ios swift

我每秒都用a NSTimer来更新一个UIButton标题.

它可以工作,但标题中的文字会0自动闪烁(动画为alpha 和背景).

我试图使用button.layer.removeAllAnimations()没有运气,也没有例外,因此QuartzCore似乎正确链接.


目前的非工作偏执代码:

UIView.setAnimationsEnabled(false)
UIView.performWithoutAnimation {
    button.setTitle(time, forState: .Normal)
    button.layer.removeAllAnimations()
        }
UIView.setAnimationsEnabled(true)
Run Code Online (Sandbox Code Playgroud)

cbi*_*gin 40

确保您的按钮是"自定义"按钮而不是"系统"按钮.

如果您在故事板上创建它,则只需更改按钮类型.如果您以编程方式创建它,那么它应该是:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
Run Code Online (Sandbox Code Playgroud)

  • 真好!但是我不明白为什么系统按钮会拒绝服从标准的UIKit命令。 (2认同)

Xha*_*Liu 16

我做了一个Swift扩展来做到这一点:

extension UIButton {
    func setTitleWithOutAnimation(title: String?) {
        UIView.setAnimationsEnabled(false)

        setTitle(title, forState: .Normal)

        layoutIfNeeded()
        UIView.setAnimationsEnabled(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

在iOS 8和9上适用于我UIButtonTypeSystem.


Dar*_*rio 7

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

UIView.performWithoutAnimation {
    //Button changes
    button.layoutIfNeeded()
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.