Prevent UIButton's setTitle:forState: animation [duplicate]

你离开我真会死。 提交于 2020-01-22 13:45:26

问题


I am using a NSTimer to update a UIButton's title every second.

It works but the text in the title blinks (animates to alpha 0 and back) automatically.

I tried to use button.layer.removeAllAnimations() with no luck, and no exceptions, so QuartzCore seems to be correctly linked.


Current non-working paranoid code:

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

回答1:


Make sure your button is a "custom" button and not a "system" button.

If you created it on a storyboard, then just change the Button Type. If you created it programmatically, then it should be:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];



回答2:


I’ve made a Swift extension to do this:

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

        setTitle(title, forState: .Normal)

        layoutIfNeeded()
        UIView.setAnimationsEnabled(true)
    }
}

Works for me on iOS 8 and 9, with UIButtonTypeSystem.




回答3:


You can perform Button changes inside the closure:

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

Hope this helps.



来源:https://stackoverflow.com/questions/29630500/prevent-uibuttons-settitleforstate-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!