【问题标题】:Animating button border in swift快速动画按钮边框
【发布时间】:2015-04-03 14:39:20
【问题描述】:

我最近学习了如何使用 Alpha 为按钮设置动画,以便它在 Swift 中淡入/淡出。但是,如果我只想更改边框本身的 alpha,则动画似乎不起作用。相反,它从一个州“跳”到另一个州。

UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: {            
  var borderColor = UIColor(red: 0.41, green: 1.28, blue: 1.85, alpha: 0.0)
  self.startButton.layer.borderColor = borderColor.CGColor
}, completion: nil);

例如,上面的代码没有动画,而是在边框的 alpha 1.0 和 0.0 之间产生“跳跃”。

但是,这可以正常工作(更改整个按钮的 alpha):

UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: {
  self.startButton.alpha = 1;
}, completion: nil);

有没有办法解决这个问题?

【问题讨论】:

  • 不是所有的东西都可以用UIView.animateWithDuration动画化

标签: swift animation


【解决方案1】:

这是一个简单的解决方案:

let borderWidth:CABasicAnimation = CABasicAnimation(keyPath: "borderWidth")
borderWidth.fromValue = 0
borderWidth.toValue = 0.9
borderWidth.duration = 0.5
yourView.layer.borderWidth = 0.5
yourView.layer.borderColor = UIColor.whiteColor().CGColor
yourView.layer.addAnimation(borderWidth, forKey: "Width")
yourView.layer.borderWidth = 0.0

它对我有用。

【讨论】:

    【解决方案2】:

    您不能使用UIView 动画为layer 的某些部分设置动画。另外,我认为不可能为边框的 alpha 值设置动画。为了达到类似的效果,您可以为边框的宽度设置动画:

    我做了这个UIView 扩展:

    extension UIView {
      func animateBorderWidth(toValue: CGFloat, duration: Double = 0.3) {
        let animation = CABasicAnimation(keyPath: "borderWidth")
        animation.fromValue = layer.borderWidth
        animation.toValue = toValue
        animation.duration = duration
        layer.add(animation, forKey: "Width")
        layer.borderWidth = toValue
      }
    }
    

    然后使用以下命令显示视图的边框:

    startButton.animateBorderWidth(toValue: 1, duration: 0.5)
    

    并通过使用隐藏它:

    startButton.animateBorderWidth(toValue: 0)
    

    【讨论】:

      【解决方案3】:

      borderColorborderWidth 等功能是按钮 的属性。这告诉您必须使用 layer 的核心动画 - 而不是查看动画,就像您的代码尝试做的那样 - 为这些功能设置动画。它工作得很好;在这个动画中,我演示了当您使用核心动画同时动画borderWidthcornerRadius 时会发生什么:

      borderColor 的动画效果类似。

      【讨论】:

      • 请问我将如何对图层而不是视图进行动画处理?
      • 阅读我上面的答案。您将使用核心动画。核心动画是直接层动画。视图动画仅适用于五个特定的视图属性。核心动画适用于任何动画层属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2019-04-09
      相关资源
      最近更新 更多