【问题标题】:How do you move a CALayer instantly (without animation)如何立即移动 CALayer(无动画)
【发布时间】:2010-09-18 14:06:53
【问题描述】:

我正在尝试在 iOS 应用中拖动 CALayer

一旦我更改了它的位置属性,它就会尝试动画到新位置并在整个地方闪烁:

 layer.position = CGPointMake(x, y)

如何立即移动CALayers?我似乎无法理解 Core Animation API。

【问题讨论】:

标签: ios objective-c cocoa-touch core-animation calayer


【解决方案1】:

您希望将您的通话包装在以下内容中:

[CATransaction begin]; 
[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
layer.position = CGPointMake(x, y);
[CATransaction commit];

【讨论】:

  • 就是这样。我什至没有想到 CATransaction。非常感谢!
  • 是的,6 年半之后。还是有帮助的。 :D
  • iOS7 支持新的速记:[UIView performWithoutAnimation:<#^(void)actionsWithoutAnimation#>];
  • 7 年 7 个月 17 天后:仍然有用。谢谢!
  • 9年后点赞
【解决方案2】:

Swift 3 扩展:

extension CALayer {
    class func performWithoutAnimation(_ actionsWithoutAnimation: () -> Void){
        CATransaction.begin()
        CATransaction.setValue(true, forKey: kCATransactionDisableActions)
        actionsWithoutAnimation()
        CATransaction.commit()
    }
}

用法:

CALayer.performWithoutAnimation(){
    someLayer.position = newPosition
}

【讨论】:

  • @noescape 属性添加到块中以允许(并明确)在块中不需要self 很有用
【解决方案3】:

你也可以使用便利功能

[CATransaction setDisableActions:YES] 

也是。

注意:请务必阅读 Yogev Shelly 的 cmets 以了解可能出现的任何问题。

【讨论】:

  • 重要,这会影响所有 CALayer,因此您希望在完成后重新启用操作,即 [CATransaction setDisableActions:YES]
  • 该死的我应该这么说。好保存。该命令在设置为 NO 或核心图形动画引擎完成一个运行周期之前禁用动画。不确定这是否是正确的词:/但感谢您为大家澄清这一点。
【解决方案4】:

正如其他人所建议的,您可以使用CATransaction
问题出现是因为 CALayer 的默认隐式动画持续时间为 0.25 秒。

因此,setDisableActions 的一个更简单的(在我看来)替代方法是使用 setAnimationDuration,其值为 0.0

[CATransaction begin];
[CATransaction setAnimationDuration:0.0];
layer.position = CGPointMake(x, y);
[CATransaction commit];

【讨论】:

  • 易于记忆,在重新阅读代码时易于理解,并且更易于键入。谢谢!
【解决方案5】:

在此处结合 Swift 4 的先前答案,以明确明确动画持续时间...

extension CALayer
{
    class func perform(withDuration duration: Double, actions: () -> Void) {
        CATransaction.begin()
        CATransaction.setAnimationDuration(duration)
        actions()
        CATransaction.commit()
    }
}

用法...

CALayer.perform(withDuration: 0.0) {
            aLayer.frame = aFrame
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 2012-01-09
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多