在ios7中,我的UIButton标题在错误的时间动画进出——迟到。在iOS 6上不出现此问题。我用的是:
[self setTitle:text forState:UIControlStateNormal];
我更希望这能立即发生,而不是一个空白的框架。这种眨眼特别分散注意力,并将注意力从其他动画中转移开。
在ios7中,我的UIButton标题在错误的时间动画进出——迟到。在iOS 6上不出现此问题。我用的是:
[self setTitle:text forState:UIControlStateNormal];
我更希望这能立即发生,而不是一个空白的框架。这种眨眼特别分散注意力,并将注意力从其他动画中转移开。
当前回答
一个方便的扩展动画按钮标题变化在Swift,发挥与默认实现很好:
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)
}
}
}
其他回答
这适用于自定义按钮:
[UIView setAnimationsEnabled:NO];
[_button setTitle:@"title" forState:UIControlStateNormal];
[UIView setAnimationsEnabled:YES];
对于系统按钮,你需要在重新启用动画之前添加这个(谢谢@Klaas):
[_button layoutIfNeeded];
我已经做了一个Swift扩展来做这个:
extension UIButton {
func setTitleWithoutAnimation(title: String?) {
UIView.setAnimationsEnabled(false)
setTitle(title, forState: .Normal)
layoutIfNeeded()
UIView.setAnimationsEnabled(true)
}
}
适用于我的iOS 8和9,与UIButtonTypeSystem。
(代码是Swift 2, Swift 3和Objective-C应该类似)
将按钮类型设置为UIButtonTypeCustom,它将停止闪烁
斯威夫特5
myButton.titleLabel?.text = "title"
myButton.setTitle("title", for: .normal)
我得到了它的工作组合的答案:
[[[button titleLabel] layer] removeAllAnimations];
[UIView performWithoutAnimation:^{
[button setTitle:@"Title" forState:UIControlStateNormal];
}];