LoginSignup
20
20

More than 5 years have passed since last update.

SwiftでCALayerの暗黙的アニメーションを無効にする ( OSX )

Last updated at Posted at 2016-02-18

CALayerのプロパティは変更すると暗黙的にアニメーションをしてくれます。便利ですね。
でも、シーンによってはこのアニメーションを一時的に無効にしたいケースがあると思います。

CATransaction.begin と CATransaction.commit

CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
//ここにCALayerのプロパティの変更のコードを記述
CATransaction.commit()

上記のように、CATransaction.begin と CATransaction.commit の間に変更されたCALayerのプロパティはアニメーションをしなくなります。が、覚えるのが面倒です!

iOSは便利だよなぁ、、

UIViewのクラスメソッドにはperformWithoutAnimationというメソッドがあり、アニメーションを無効にしたい一連のプロパティ変更処理をクロージャで渡すことができます

//@available(iOS 7.0, *)
//public class func performWithoutAnimation(actionsWithoutAnimation: () -> Void)

UIView.performWithoutAnimation {
//ここにUIViewのプロパティの変更のコードを記述
}

OSXにも移植しよう!

extensionを使って、CALayerにもperformWithoutAnimationメソッドを追加してみました


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

CALayer.performWithoutAnimation {
//ここにCALayerのプロパティの変更のコードを記述
}

わーい、iOSみたいになったよー。

20
20
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20