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

[self setTitle:text forState:UIControlStateNormal];

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


当前回答

我发现这个解决方案与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)

其他回答

在Swift中,你可以使用:

UIView.performWithoutAnimation {
    self.someButtonButton.setTitle(newTitle, forState: .normal)
    self.someButtonButton.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)

我已经做了一个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应该类似)

从iOS 7.1开始,唯一适合我的解决方案是用UIButtonTypeCustom类型初始化按钮。