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!
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.
UIView.animateWithDuration(0.5,
delay: 0.0,
options: .CurveEaseInOut,
animations: { self.frame = CGRectMake(0,0, 500, 500)},
completion: { complete in
self.removeFromSuperview()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With