15

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)
Rivera
  • 10,792
  • 3
  • 58
  • 102
  • Did you try to wrap it with `UIView`'s `performWithoutAnimation(_ actionsWithoutAnimation: () -> Void)` (iOS >= 7)? Or `setAnimationsEnabled(_ enabled: Bool)`? – zrzka Apr 14 '15 at 14:57

3 Answers3

50

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];
cbiggin
  • 1,942
  • 1
  • 17
  • 18
  • 4
    Nice! Yet I can't understand why a system button refuses to obey to standard UIKit orders. – Rivera Apr 15 '15 at 14:00
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, with UIButtonTypeSystem.

Xhacker Liu
  • 1,578
  • 1
  • 16
  • 25
12

You can perform Button changes inside the closure:

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

Hope this helps.

R Pelzer
  • 1,188
  • 14
  • 34
Dario
  • 3,105
  • 1
  • 17
  • 16