【问题标题】:Prevent UIButton's setTitle:forState: animation [duplicate]防止 UIButton 的 setTitle:forState: 动画 [重复]
【发布时间】:2015-06-20 05:59:18
【问题描述】:

我正在使用NSTimer 每秒更新UIButton 的标题。

它可以工作,但标题中的文本会自动闪烁(动画为 alpha 0 并返回)。

我尝试使用 button.layer.removeAllAnimations() 没有运气,也没有例外,所以 QuartzCore 似乎正确链接。


当前无效的偏执代码:

UIView.setAnimationsEnabled(false)
UIView.performWithoutAnimation {
    button.setTitle(time, forState: .Normal)
    button.layer.removeAllAnimations()
        }
UIView.setAnimationsEnabled(true)

【问题讨论】:

  • 您是否尝试用UIViewperformWithoutAnimation(_ actionsWithoutAnimation: () -> Void) 包装它(iOS >= 7)?还是setAnimationsEnabled(_ enabled: Bool)

标签: ios objective-c swift animation uibutton


【解决方案1】:

您可以在闭包内执行 Button 更改:

UIView.performWithoutAnimation {
    //Button changes
    button.layoutIfNeeded()
}

希望这会有所帮助。

【讨论】:

  • 太糟糕了,同样的结果。
  • 另外,调用 UIView.performWithoutAnimation { //Button changes } 还是需要调用 layoutIfNeeded()
  • 我认为这是正确的答案!
  • 只需要设置 setTitle 调用后的 layoutIfNeeded 即可。将其包装在 UIView.performWithoutAnimation 中似乎没有任何作用。
【解决方案2】:

我为此做了一个 Swift 扩展:

extension UIButton {
    func setTitleWithOutAnimation(title: String?) {
        UIView.setAnimationsEnabled(false)

        setTitle(title, forState: .Normal)

        layoutIfNeeded()
        UIView.setAnimationsEnabled(true)
    }
}

在 iOS 8 和 9 上为我工作,UIButtonTypeSystem

【讨论】:

  • 也适用于我最新的 Swift 版本。也在 IB 中使用 UIButtonTypeSystem。谢谢!
  • 在 Swift 3.1 上测试,仍然有效!
  • 这会禁用整个应用程序的动画,只是为了不为按钮设置动画......它有效,但最好只使用自定义 UIButton 类型。
【解决方案3】:

确保您的按钮是“自定义”按钮而不是“系统”按钮。

如果您在情节提要上创建它,则只需更改按钮类型。如果您以编程方式创建它,那么它应该是:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];

【讨论】:

  • 不错!然而我不明白为什么系统按钮拒绝遵守标准的 UIKit 指令。
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2013-06-22
相关资源
最近更新 更多