ios - Swift 中带有核心动画的动画 UILabel 元素

标签 ios core-animation swift

我正在学习如何将 CoreAnimation 与各种 UI 元素结合使用。最终,当我过渡到下一个 View 时,我想在屏幕上的所有 ui 元素上执行复杂的排队动画。

然而,现在我正在尝试一些非常简单的事情。我想在点击按钮时转换(放大)UILabel。

我有以下功能:

func animateUIElementsOut(element : AnyObject) {

  var animation : CABasicAnimation = CABasicAnimation(keyPath: "transform");

  var transform : CATransform3D = CATransform3DMakeScale(2, 2, 1);

  animation.setValue(NSValue(CATransform3D: transform), forKey: "scaleText");

  animation.duration = 2.0;

  element.layer?.addAnimation(animation, forKey: "scaleText");

}

我像这样在点击按钮时调用函数:

  animateUIElementsOut(greetingsLabel);

编译器没有发出任何警告,但是动画不工作。我在这里做错了什么?

根据@David Rönnqvist 的建议,工作代码如下所示(添加了 fromValue/toValue):

func animateUIElementsOut(element : AnyObject) {

  var animation : CABasicAnimation = CABasicAnimation(keyPath: "transform");

  animation.delegate = self;

  var transform : CATransform3D = CATransform3DMakeScale(2, 2, 1);

  animation.fromValue = NSValue(CATransform3D: CATransform3DIdentity);
  animation.toValue = NSValue(CATransform3D: transform);

  animation.duration = 2.0;

  element.layer?.addAnimation(animation, forKey: nil);
}

最佳答案

动画既没有 toValue 也没有 fromValue

您正在为动画上的 "scaleText" 键设置变换,但动画没有相应的属性。

要使动画 本身起作用,您应该将变换设置为动画的toValue。但是,仍然缺少使整个事情正常进行的事情。层的模型值永远不会改变,所以当动画结束并被移除时,您将再次看到旧的(模型)值。

如果您只对制作缩放动画感兴趣,我建议您改用更高级别的 UIView 动画 API:

UIView.animateWithDuration(2.0) {
    element.transform = CGAffineTransformMakeScale(2, 2)
}

另一方面,如果您对使用 Core Animation 感兴趣,还需要做一些其他事情才能使其正常工作。

  1. 将动画配置为当前模型值(使用fromValue 属性)
  2. 配置动画以新值(如上所述)
  3. 在添加动画之前将模型值更新为新值。

顺便说一句,您可以在没有任何此类属性的情况下为“scaleText”设置值的原因是图层和动画的工作方式与大多数具有键值编码的类有点不同。您可以使用键值编码在层和 View 上设置和获取任何值。这意味着这是有效代码:

let layer = CALayer()
layer.setValue(1, forKey: "foo")
var foo = layer.valueForKey("foo") // is equal to 1

let anim = CABasicAnimation(keyPath: "bounds")
anim.setValue(2, forKey: "bar")
var bar = anim.valueForKey("bar") // is equal to 2

但是,如果您尝试对几乎任何其他对象执行相同的操作,您将收到一个运行时异常,指出该类不符合该键的键值编码。例如,这段代码:

let view = UIView(frame: CGRectZero)
view.setValue(3, forKey: "baz")

产生这个运行时异常:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x10dc08b30> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key baz.'

关于ios - Swift 中带有核心动画的动画 UILabel 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353768/

相关文章:

ios - removeFromSuperview() 突然不再工作

ios - CA::Transaction::commit() 中的瓶颈

ios - 为什么围绕 x 轴平移 CALayer 会影响围绕 Y 轴的旋转

iphone - 使用 CoreAnimation 在 iOS 中实现流畅的动画

ios - 如何在 ios swift 中显示来自 url 的图像

iOS拆分字符串

ios - webmethod 在 ios 调用上接收空参数

ios - swift - touchID 需要很长时间才能加载

ios - 使用 NSXMLParser 在 Swift 中解析 XML

ios - 加载后是否可以更改 UITabBarController 文本颜色?