在ios7中,我的UIButton标题在错误的时间动画进出——迟到。在iOS 6上不出现此问题。我用的是:

[self setTitle:text forState:UIControlStateNormal];

我更希望这能立即发生,而不是一个空白的框架。这种眨眼特别分散注意力,并将注意力从其他动画中转移开。


当前回答

通常简单地将按钮类型设置为自定义对我来说是有效的,但由于其他原因,我需要子类化UIButton并将按钮类型设置回默认(System),所以闪烁再次出现。

在改变标题之前设置UIView.setAnimationsEnabled(false),然后在那之后再次为true并没有避免我的闪烁,无论我是否调用self.layoutIfNeeded()。

在iOS 9和10测试版中,我只按以下顺序做到了这一点:

1)为UIButton创建一个子类(不要忘记在Storyboard中为按钮设置自定义类)。

2)重写setTitle:forState:如下:

override func setTitle(title: String?, forState state: UIControlState) {

    UIView.performWithoutAnimation({

        super.setTitle(title, forState: state)

        self.layoutIfNeeded()
    })
}

在Interface Builder中,您可以将按钮类型留给System,不需要将其更改为自定义类型以实现此方法。

我希望这能帮助其他人,我已经与烦人的闪烁按钮斗争了很长时间,我希望避免它对其他人;)

其他回答

这适用于自定义按钮:

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

对于系统按钮,你需要在重新启用动画之前添加这个(谢谢@Klaas):

[_button layoutIfNeeded];

你实际上可以在动画块之外设置标题,只是要确保在performWithoutAnimation中调用layoutIfNeeded():

button1.setTitle("abc", forState: .Normal)
button2.setTitle("abc", forState: .Normal)
button3.setTitle("abc", forState: .Normal)
UIView.performWithoutAnimation {
    self.button1.layoutIfNeeded()
    self.button2.layoutIfNeeded()
    self.button3.layoutIfNeeded()
}

如果你有一堆按钮,考虑在超视图上调用layoutIfNeeded():

button1.setTitle("abc", forState: .Normal)
button2.setTitle("abc", forState: .Normal)
button3.setTitle("abc", forState: .Normal)
UIView.performWithoutAnimation {
    self.view.layoutIfNeeded()
}

请注意:

当_button的"buttonType"为"UIButtonTypeSystem"时,以下代码无效:

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

当_button的"buttonType"为"UIButtonTypeCustom"时,上述代码有效。

我发现这个解决方案与UIButtonTypeSystem一样,但只有当按钮出于某种原因被启用时才会工作。

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

因此,如果您需要在设置标题时禁用按钮,则必须添加这些。

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

(iOS 7, Xcode 5)

结合以上的答案,可以为UIButtonTypeSystem提供以下解决方案:

if (_button.enabled)
{
    [UIView setAnimationsEnabled:NO];
    [_button setTitle:@"title" forState:UIControlStateNormal];
    [UIView setAnimationsEnabled:YES];
}
else // disabled
{
    [UIView setAnimationsEnabled:NO];
    _button.enabled = YES;
    [_button setTitle:@"title" forState:UIControlStateNormal];
    _button.enabled = NO;
    [UIView setAnimationsEnabled:YES];
}