How to stop unwanted UIButton animation on title change?

前端 未结 24 2545
面向向阳花
面向向阳花 2020-11-28 19:07

In iOS 7 my UIButton titles are animating in and out at the wrong time - late. This problem does not appear on iOS 6. I\'m just using:

[self setTitle:text fo         


        
相关标签:
24条回答
  • 2020-11-28 19:39

    Use the performWithoutAnimation: method and then force layout to happen immediately instead of later on.

    [UIView performWithoutAnimation:^{
      [self.myButton setTitle:text forState:UIControlStateNormal];
      [self.myButton layoutIfNeeded];
    }];
    
    0 讨论(0)
  • 2020-11-28 19:40

    I got it to work with a combination of answers:

    [[[button titleLabel] layer] removeAllAnimations];
    
        [UIView performWithoutAnimation:^{
    
            [button setTitle:@"Title" forState:UIControlStateNormal];
    
        }];
    
    0 讨论(0)
  • 2020-11-28 19:41

    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.

    0 讨论(0)
  • 2020-11-28 19:41

    The Xhacker Liu extension converted to Swift 3 :

    extension UIButton {
        func setTitleWithoutAnimation(title: String?) {
            UIView.setAnimationsEnabled(false)
    
            setTitle(title, for: .normal)
    
            layoutIfNeeded()
            UIView.setAnimationsEnabled(true)
        }
    }
    
    0 讨论(0)
  • 2020-11-28 19:43

    This works for custom buttons:

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

    For system buttons you need to add this before re-enabling animations (thank you @Klaas):

    [_button layoutIfNeeded];
    
    0 讨论(0)
  • 2020-11-28 19:43

    Starting in iOS 7.1 the only solution that worked for me was initializing the button with type UIButtonTypeCustom.

    0 讨论(0)
提交回复
热议问题