如何禁用CALayer隐式animation?

这让我疯狂! 我正在绘制应用程序。 假设我正在使用一个名为sheet的UIView

我添加了一些子层到这个视图( [sheet.layer addSublayer:...] ),然后我想绘制它们。 为此,我创build了一个CGImageRef并将其放入图层的contents 。 但它是animation,我不想要的。

我尝试了一切:

  • removeAnimationForKey:
  • removeAllAnimations
  • 设置动作字典
  • 使用操作层delegate
  • [CATransaction setDisableAnimations:YES]

这似乎是正确的。 我不明白为什么这层还是animation的;
难道我做错了什么? 有没有秘密的方法?

您必须通过将代码包装在CATransaction中来显式禁用animation

 [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; layer.content = someImageRef; [CATransaction commit]; 

迅速

 CATransaction.begin() CATransaction.setDisableActions(true) // change layer properties that you don't want to animate CATransaction.commit() 

从Mac OS X 10.6和iOS 3开始, CATransaction还有一个setDisableActions方法,用于设置关键kCATransactionDisableActions的值。

 [CATransaction begin]; [CATransaction setDisableActions:YES]; layer.content = someImageRef; [CATransaction commit]; 

在Swift中,我喜欢使用这种扩展方法:

 extension CATransaction { class func withDisabledActions<T>(_ body: () throws -> T) rethrows -> T { CATransaction.begin() CATransaction.setDisableActions(true) defer { CATransaction.commit() } return try body() } } 

你可以像这样使用它:

 CATransaction.withDisabledActions { // your stuff here } 

其他方式:

  1. 您应该禁用sheet.layer的默认animation,在添加子图层时隐式调用。

  2. 你也应该每个子层的内容animation。 当然,每次您设置sublayer.content时,您都可以使用CATransaction的“kCATransactionDisableActions”。 但是,当您创build子图层时,您可以禁用此animation一次。


这是代码:

 // disable animation of container sheet.layer.actions = [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"sublayers"]; // disable animation of each sublayer sublayer.layer.actions = [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"content"]; // maybe, you'll also have to disable "onOrderIn"-action of each sublayer. 

Swift 2

我能够禁用所有的animation如下,其中myView是您正在使用的视图:

 myView.layer.sublayers?.forEach { $0.removeAllAnimations() } 

作为一个侧面说明,删除所有图层:

 myView.layer.sublayers?.forEach { $0.removeFromSuperlayer() } 

可重复使用的全球代码:

 /** * Disable Implicit animation * EXAMPLE: disableAnim{view.layer?.position = 20}//Default animation is now disabled */ func disableAnim(_ closure:()->Void){ CATransaction.begin() CATransaction.setDisableActions(true) closure() CATransaction.commit() } 

在代码中的任何位置添加此代码(全局范围)