Swift上的块(animateWithDuration:动画:完成:) [英] Blocks on Swift (animateWithDuration:animations:completion:)
问题描述
我无法让这些块在Swift上运行。这是一个有效的例子(没有完成块):
I'm having trouble making the blocks work on Swift. Here's an example that worked (without completion block):
UIView.animateWithDuration(0.07) {
self.someButton.alpha = 1
}
或者没有尾随闭包:
UIView.animateWithDuration(0.2, animations: {
self.someButton.alpha = 1
})
但是一旦我尝试添加完成块,它就不起作用:
but once I try to add the completion block it just won't work:
UIView.animateWithDuration(0.2, animations: {
self.blurBg.alpha = 1
}, completion: {
self.blurBg.hidden = true
})
自动完成功能让我完成: ((Bool) - > Void)?
但不确定如何使它工作。也尝试使用尾随闭包,但得到了同样的错误:
The autocomplete gives me completion: ((Bool) -> Void)?
but not sure how to make it work. Also tried with trailing closure but got the same error:
!无法找到接受所提供参数的'animateWithDuration的重载
// This is how I do regular animation blocks
UIView.animate(withDuration: 0.2) {
<#code#>
}
// Or with a completion block
UIView.animate(withDuration: 0.2, animations: {
<#code#>
}, completion: { _ in
<#code#>
})
我没有使用尾随闭包来完成块,因为我认为它缺乏清晰度,但如果你喜欢它,那么你可以看到 Trevor在下面的回答。
I don't use the trailing closure for the completion block because I think it lacks clarity, but if you like it then you can see Trevor's answer below.
推荐答案
animateWithDuration中的完成参数采用一个带有一个布尔参数的块。在swift中,就像在Obj C块中一样,你必须指定一个闭包所需的参数:
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
})
这里的重要部分是(值:Bool)
。这告诉编译器这个闭包采用Bool标记为'value'并返回void。
The important part here is the (value: Bool) in
. That tells the compiler that this closure takes a Bool labeled 'value' and returns void.
作为参考,如果你想写一个返回bool的闭包,语法会是
For reference, if you wanted to write a closure that returned a bool the syntax would be
{(value: Bool) -> bool in
//your stuff
}
这篇关于Swift上的块(animateWithDuration:动画:完成:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!