Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent UIButton from flashing when updating the title

Tags:

ios7

uibutton

When I call setTitle on a UIButton, the button flashes in iOS 7. I tried setting myButton.highlighted = NO, but that didn't stop the button from flashing.

[myButton setTitle:[[NSUserDefaults standardUserDefaults] stringForKey:@"elapsedLabelKey"] forState:UIControlStateNormal];

myButton.highlighted = NO;

Here is how I set up the timer that updated the titles:

- (void)actionTimer {
    if (myTimer == nil) {

        myTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                        target: self
                        selector: @selector(showActivity)
                        userInfo: nil
                        repeats: YES];
    }
}

Here is the method that actually updates the titles:

- (void)showActivity {

    NSString *sym = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];

    if (pauseInterval == nil) {

        // Update clock
        seconds = [[NSDate date] timeIntervalSinceDate:startInterval] - breakTime;

        // Update total earned
        secRate = rate.value / 60 / 60;
        total = secRate * seconds;
        [totalLabel setTitle:[NSString stringWithFormat:@"%@%.4f",sym,total] forState:UIControlStateNormal];

        days = seconds / (60 * 60 * 24);
        seconds -= days * (60 * 60 * 24);
        int hours = seconds / (60 * 60);
        fhours = (float)seconds / (60.0 * 60.0);
        seconds -= hours * (60 * 60);
        int minutes = seconds / 60;
        seconds -= minutes * 60;

        // Update the timer clock
        [elapsed setTitle:[NSString stringWithFormat:@"%.2i:%.2i:%.2i:%.2i",days,hours,minutes,seconds] forState:UIControlStateNormal];
    }
}
like image 309
FierceMonkey Avatar asked Oct 15 '13 00:10

FierceMonkey


3 Answers

Set the button type to UIButtonTypeCustom and it'll stop flashing

like image 150
Quanlong Avatar answered Nov 20 '22 16:11

Quanlong


A better approach than [UIView setAnimationsEnabled:NO] which may affect other animations is to only disable the specific title animation.

Objective-C:

[UIView performWithoutAnimation:^{
  [myButton setTitle:text forState:UIControlStateNormal];
  [myButton layoutIfNeeded];
}];

Swift:

UIView.performWithoutAnimation { 
    myButton.setTitle(text, for: .normal)
    myButton.layoutIfNeeded()
}
like image 62
Cœur Avatar answered Nov 20 '22 14:11

Cœur


*Please note *

when "buttonType" of _button is "UIButtonTypeSystem", below code is invalid

[UIView setAnimationsEnabled:NO];
[_button setTitle:@"title" forState:UIControlStateNormal];
[UIView setAnimationsEnabled:YES];

when "buttonType" of _button is "UIButtonTypeCustom", above code is valid.

like image 30
shede333 Avatar answered Nov 20 '22 15:11

shede333