How to stop unwanted UIButton animation on title change?

前端 未结 24 2546
面向向阳花
面向向阳花 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:43

    Set UIButton type as Custom. That should remove fade in and out animations.

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

    Swift 5

    myButton.titleLabel?.text = "title"
    myButton.setTitle("title", for: .normal)
    
    0 讨论(0)
  • 2020-11-28 19:45

    A convenient extension for animated button title change in Swift that plays nicely with the default implementation:

    import UIKit
    
    extension UIButton {
      /// By default iOS animated the title change, which is not desirable in reusable views
      func setTitle(_ title: String?, for controlState: UIControlState, animated: Bool = true) {
        if animated {
          setTitle(title, for: controlState)
        } else {
          UIView.setAnimationsEnabled(false)
          setTitle(title, for: controlState)
          layoutIfNeeded()
          UIView.setAnimationsEnabled(true)
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-28 19:46

    so i find worked solution:

    _logoutButton.titleLabel.text = NSLocalizedString(@"Logout",);
    [_logoutButton setTitle:_logoutButton.titleLabel.text forState:UIControlStateNormal];
    

    in first we change title for button, then resize button for this title

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

    Usually simply setting the button type to Custom works for me, but for other reasons I needed to subclass UIButton and set the button type back to the default (System), so the blinking reappeared.

    Setting UIView.setAnimationsEnabled(false) before changing the title and then to true again after that didn't avoid the blinking for me, no matter if I called self.layoutIfNeeded() or not.

    This, and only this in the following exact order, worked for me with iOS 9 and 10 beta:

    1) Create a subclass for UIButton (don't forget to set the custom class for the button in the Storyboard too).

    2) Override setTitle:forState: as follows:

    override func setTitle(title: String?, forState state: UIControlState) {
    
        UIView.performWithoutAnimation({
    
            super.setTitle(title, forState: state)
    
            self.layoutIfNeeded()
        })
    }
    

    In Interface Builder, you can leave the button type to System, no need to change it to Custom Type for this approach to work.

    I hope this helps someone else, I've struggled for so long with the annoying blinking buttons that I hope to avoid it to others ;)

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

    Change button type to custom form interface builder.

    enter image description here

    This worked for me.

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