Blocks on Swift (animateWithDuration:animations:completion:)
The completion parameter in animateWithDuration
takes a block which takes one boolean parameter. In Swift, like in Obj-C blocks, you must specify the parameters that a closure takes:
UIView.animateWithDuration(0.2, animations: {
self.blurBg.alpha = 1
}, completion: {
(value: Bool) in
self.blurBg.hidden = true
})
The important part here is the (value: Bool) in
. That tells the compiler that this closure takes a Bool labeled 'value' and returns Void.
For reference, if you wanted to write a closure that returned a Bool, the syntax would be
{(value: Bool) -> bool in
//your stuff
}
The completion is correct, the closure must accept a Bool
parameter: (Bool) -> ()
. Try
UIView.animate(withDuration: 0.2, animations: {
self.blurBg.alpha = 1
}, completion: { finished in
self.blurBg.hidden = true
})
Underscore by itself alongside the in
keyword will ignore the input
Swift 2
UIView.animateWithDuration(0.2, animations: {
self.blurBg.alpha = 1
}, completion: { _ in
self.blurBg.hidden = true
})
Swift 3, 4, 5
UIView.animate(withDuration: 0.2, animations: {
self.blurBg.alpha = 1
}, completion: { _ in
self.blurBg.isHidden = true
})
There is my solution above based on accepted answer above. It fades out a view and hiddes it once almost invisible.
Swift 2
func animateOut(view:UIView) {
UIView.animateWithDuration (0.25, delay: 0.0, options: UIViewAnimationOptions.CurveLinear ,animations: {
view.layer.opacity = 0.1
}, completion: { _ in
view.hidden = true
})
}
Swift 3, 4, 5
func animateOut(view: UIView) {
UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.curveLinear ,animations: {
view.layer.opacity = 0.1
}, completion: { _ in
view.isHidden = true
})
}
Here you go, this will compile
Swift 2
UIView.animateWithDuration(0.3, animations: {
self.blurBg.alpha = 1
}, completion: {(_) -> Void in
self.blurBg.hidden = true
})
Swift 3, 4, 5
UIView.animate(withDuration: 0.3, animations: {
self.blurBg.alpha = 1
}, completion: {(_) -> Void in
self.blurBg.isHidden = true
})
The reason I made the Bool area an underscore is because you not using that value, if you need it you can replace the (_) with (value : Bool)