Reputation: 1061
How to refactore code to be more compact by sending the function the view , number of animated times , applied action function and success funtion
If functional programming solution can be proposed it will be helpful
typealias AnimateAction = UIView -> Void
typealias AnimateSuccess = Bool -> Void
func animateThreetimes(animatedView:UIView,animateAction:AnimateAction,animateSuccess:AnimateSuccess)
{
UIView.animateWithDuration(0.5, animations: { () -> Void in
animateAction(animatedView)
}) { (success) -> Void in
UIView.animateWithDuration(1, animations: { () -> Void in
animateAction(animatedView)
}, completion: { (success) -> Void in
UIView.animateWithDuration(0.5, animations: { () -> Void in
animateAction(animatedView)
}, completion: { (success) -> Void in
animateSuccess(success)
})
})
}
}
Upvotes: 0
Views: 125
Reputation: 5554
Assuming that you want a general approach that could be used for an arbitrary number of animations ...
You could include a counter variable in the function call, decrement it when you have animated, and while it is non-zero, call the animate function again
Upvotes: 0
Reputation: 1129
You could also do something like this to have a bit more control of the variables you are passing in and how you want to handle the completion. Furthermore this answers your request for a functional solution to the problem.
typealias AnimationAction = UIView -> Void
typealias AnimationSuccess = Bool -> Void
func animateView(view: UIView, animationAction: AnimationAction) -> (duration: NSTimeInterval, completionHandler: AnimationSuccess?) -> Void {
// Return a function that takes a duration and a maybe completion handler
return { duration, completionHandler in
return UIView.animateWithDuration(duration, animations: {
animationAction(view)
}, completion: { finished in
completionHandler?(finished) // Optional function only called if exists
})
}
}
// Just showing the mechanism
let durations = [0.5, 1, 0.5]
for index in 0..<durations.count {
let view = UIView(frame: CGRectZero)
let animationAction: AnimationAction = { view in
print("View: \(view)")
}
let completionHandler: AnimationSuccess? = {
if durations[index] == durations.last {
return { finished in
print(finished)
}
} else {
return nil
}
}()
animateView(view, animationAction: animationAction)(duration: durations[index], completionHandler: completionHandler)
}
Upvotes: 1
Reputation: 16774
Recursion would do quite nicely:
func animate(count: Int) {
if count > 0 {
UIView.animateWithDuration(0.2, animations: { () -> Void in
// do the animations
}, completion: { (_) -> Void in
self.animate(count-1);
})
}
}
Upvotes: 1