Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write completion handler in Swift with animation.

Tags:

ios

swift

I have an animation, and when its complete I want to remove it from its superView. However I just can't get my head around the completion handler syntax for Swift. This animation is written in a UIView subclass.

UIView.animateWithDuration(0.5,
        delay: 0.0,
        options: .CurveEaseInOut,
        animations: { self.frame = CGRectMake(0,0, 500, 500)},
        completion: /*Magic Code here??*/)

I want to call self.removeFromSuperView() as the parameter for completion, however after reading many articles online I still cannot achieve this.

Thank You!

like image 495
Stephen Fox Avatar asked Dec 06 '22 22:12

Stephen Fox


2 Answers

UIView.animate(
    withDuration: 0.5,
    delay: 0.0,
    options: .curveEaseInOut,
    animations: { self.frame = CGRect(x: 0, y: 0, width: 500, height: 500) },
    completion: { [weak self] finished in
        self?.removeFromSuperview()
    })

The completion closure takes one argument, a Bool (called finished in the code above) indicating whether the animation actually completed, or was interrupted.

It's worth considering that since you are referencing self in the completion closure, it is possible* that the animation may affect the lifetime of your view (consider that the animation is still running when the view would otherwise be deallocated, but the closure's strong reference is keeping the view alive). For this reason I included a capture list to ensure a weak reference to self is used.

*Possible, but perhaps unlikely... the view should only be deallocated in response to being removed from the view hierarchy, which I would expect to implicitly cancel the animation anyway and call the completion closure with finished == false. However, I would personally err on the side of caution and include [weak self] anyway, because I'm paranoid.

like image 93
Stuart Avatar answered Dec 22 '22 05:12

Stuart


UIView.animateWithDuration(0.5,
    delay: 0.0,
    options: .CurveEaseInOut,
    animations: { self.frame = CGRectMake(0,0, 500, 500)},
    completion: { complete in
        self.removeFromSuperview()
    })
like image 37
Sam Avatar answered Dec 22 '22 06:12

Sam