How to prevent UIButton from flashing when updating the title

前端 未结 9 1034
旧巷少年郎
旧巷少年郎 2021-01-30 04:41

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.

[myBu         


        
相关标签:
9条回答
  • 2021-01-30 05:37

    I'm new to coding and Stackoverflow, so don't have enough reputation to comment directly to expand on https://stackoverflow.com/users/4673064/daniel-tseng excellent answer. So I have to write my own new answer, and it is this:

    extension UIButton {
        func setTitleWithoutAnimation(_ title: String?, for controlState: UIControlState) {
            UIView.performWithoutAnimation {
                self.setTitle(title, for: controlState)
                self.layoutIfNeeded()
            }
        }
    }
    

    Works great, EXCEPT:

    If all my calls later on in the code to "setTitleWithoutAnimation" do not specify a sender, then I get these weird messages related to CoreMedia or CoreData, e.g., "Failed to inherit CoreMedia permissions from 2526: (null)"

    This is probably pretty basic to coding and iOS, but for me as a new coder, it sent me on a rabbit trail for a while, as in: Today Extension Failed to inherit CoreMedia permissions from, where people had interesting answers but that did NOT reach the root of my problem.

    So I finally found that I had to go through and give my parameter-less functions parameters, i.e., I had to specify a sender. That sender could be UIButton, Any, or AnyObject. All of those worked, but ultimately there appears to be a conflict between adding a button extension with "self" and not specifically saying later on that a button is using it.

    Again, probably basic, but new to me, so I figured it would be worth sharing.

    0 讨论(0)
  • 2021-01-30 05:39

    See the responses from How to stop unwanted UIButton animation on title change? :

    [UIView setAnimationsEnabled:NO];
    [elapsed setTitle:[NSString stringWithFormat:@"%.2i:%.2i:%.2i:%.2i",days,hours,minutes,seconds] forState:UIControlStateNormal];
    [UIView setAnimationsEnabled:YES];
    
    0 讨论(0)
  • 2021-01-30 05:45

    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()
    }
    
    0 讨论(0)
提交回复
热议问题