Skip to content

Instantly share code, notes, and snippets.

@aidaan
Created February 10, 2019 22:32
Show Gist options
  • Save aidaan/3eb02d965ab09bb4569947fa61f1427c to your computer and use it in GitHub Desktop.
Save aidaan/3eb02d965ab09bb4569947fa61f1427c to your computer and use it in GitHub Desktop.
Closure based CATransaction API
import UIKit
// I'm not sure how useful this is, but swift allows for a somewhat elegant closure base API for CATransation.
// Each argument if optional, so it can be omitted unless necessary. It's a little weird having the completion
// block come before the actions block, but this way the actions block can make sure of trailing closure syntax.
extension CATransaction {
static func transaction(duration: CFTimeInterval? = nil,
timingFunction: CAMediaTimingFunction? = nil,
disableActions: Bool? = nil,
completion: (() -> Void)? = nil,
actions: () -> Void) {
begin()
duration.flatMap { setAnimationDuration($0) }
timingFunction.flatMap { setAnimationTimingFunction($0) }
disableActions.flatMap { setDisableActions($0) }
completion.flatMap { setCompletionBlock($0) }
actions()
commit()
}
}
// sample usage
let layer = CALayer()
CATransaction.transaction {
layer.backgroundColor = UIColor.red.cgColor
}
CATransaction.transaction(disableActions: true) {
layer.backgroundColor = UIColor.blue.cgColor
}
CATransaction.transaction(duration: 3) {
layer.backgroundColor = UIColor.green.cgColor
}
CATransaction.transaction(duration: 3, timingFunction: CAMediaTimingFunction(name: .easeInEaseOut)) {
layer.backgroundColor = UIColor.yellow.cgColor
}
CATransaction.transaction(completion: {
print("completed")
}) {
layer.backgroundColor = UIColor.cyan.cgColor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment