I have a generic NSObject animation class I created for a new project and I'm attempting to refactor some older projects with the new class. All was well until I found some animations w/ completion blocks, which threw off my plan to remove exorbitant amounts of redundant code from my view controllers. Here's what I've got...
Animator.swift
class Animator: NSObject {
var control: UIControl? // Can accept everything that's a subclass of UIControl
override init() {
super.init()
}
// FIXME: figure out how to add a completion block as a parameter on a method call
func animateControl(control: UIControl) {
control.transform = CGAffineTransformMakeScale(0.75, 0.75)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 5.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: {
control.transform = CGAffineTransformIdentity
}) { (value: Bool) -> Void in
// completion block
// ** method as a parameter goes here? **
}
}
}
To use it, rather than typing in all stuff to animate a button, I just call the class from MyViewController.swift
MyViewController.swift
// Property declaration
let animator = Animator()
// Tie it to an IBAction
@IBAction func myButtonAction(sender: UIButton) {
animator.animateControl(sender, methodIWantToRunAfterAnimateControlFinishes)
}
func methodIWantToRunAfterAnimateControlFinishes() {
// Do Stuff
}
How would I feed animateControl's initializer a method to run as a completion block? I looked at this (not my website, but it's how I feel), but I'm unable to get it to work.
Update
I had to wrestle with the syntax a little bit, but here's the initializer code that got me over the finish line:
func animateControl(control: UIControl, completion: (() -> Void)?) {
control.transform = CGAffineTransformMakeScale(0.75, 0.75)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 5.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: {
control.transform = CGAffineTransformIdentity
}) { _ in
// completion block
completion?()
}
}
This handles completion blocks w/ code and nil completion blocks.