15

I am using aNSTimer to update aUIButton's title every second.

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

I tried to usebutton.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)
askedApr 14, 2015 at 14:48
E. Rivera's user avatar
1
  • Did you try to wrap it withUIView'sperformWithoutAnimation(_ actionsWithoutAnimation: () -> Void) (iOS >= 7)? OrsetAnimationsEnabled(_ enabled: Bool)?CommentedApr 14, 2015 at 14:57

3 Answers3

51

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];
answeredApr 14, 2015 at 17:22
cbiggin's user avatar
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Yet I can't understand why a system button refuses to obey to standard UIKit orders.
This is unbelievable. I had an issue where setting the title was taking a long time. I debugged and tested things for many hours. I saw this answer and thought it couldn’t work…. It worked. Now my button updates quickly. Can anyone explain why this works?
19

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, withUIButtonTypeSystem.

answeredJul 30, 2015 at 22:21
Xhacker Liu's user avatar

3 Comments

Works for me also with latest Swift release. Also using UIButtonTypeSystem in IB. Thanks!
Tested on Swift 3.1, still works!
This disables animations for the whole app just to not animate a button... it works, but it would be better to just use the custom UIButton type.
13

You can perform Button changes inside the closure:

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

Hope this helps.

R Pelzer's user avatar
R Pelzer
1,2881 gold badge16 silver badges34 bronze badges
answeredApr 14, 2015 at 15:00
Dario's user avatar

4 Comments

Too bad, same result.
Also, it's shorter to call UIView.performWithoutAnimation { //Button changes } You still need to call layoutIfNeeded()
I find this the correct answer!
The layoutIfNeeded after setting the setTitle call is all that's required. Wrapping it in UIView.performWithoutAnimation doesn't seem to do anything here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.