在Swift中为按钮边框添加动画效果

9

最近我学会了如何使用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 进行动画处理。 - GriffeyDog
3个回答

13

这里有一个简单的解决方案:

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

它对我有效。


13

使用UIView动画无法对图层的部分进行动画。而且,我认为不可能对边框的透明度值进行动画处理。要实现类似的效果,可以对边框的宽度进行动画处理:

我创建了这个 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)

4

borderColorborderWidth这样的功能是按钮的图层的属性。 这告诉您必须使用图层的核心动画而不是视图动画来动画化此类功能,因为您的代码尝试执行视图动画。它运行得非常完美;在此动画中,我演示了当您使用核心动画同时动画化borderWidthcornerRadius时会发生什么:

enter image description here

borderColor的动画也可以类似地工作。


1
我可以问一下如何对图层进行动画处理而不是视图吗? - vanillaboy
请阅读我上面的回答。您可以使用核心动画。核心动画是直接层动画。视图动画仅适用于五个特定的视图属性。核心动画适用于任何可动画化的层属性。 - matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接