我在Swift上遇到了让这些模块工作的问题。下面是一个有效的例子(没有补全块):
UIView.animateWithDuration(0.07) {
self.someButton.alpha = 1
}
或者不使用尾部闭包:
UIView.animateWithDuration(0.2, animations: {
self.someButton.alpha = 1
})
但是一旦我尝试添加补全块,它就不能工作了:
UIView.animateWithDuration(0.2, animations: {
self.blurBg.alpha = 1
}, completion: {
self.blurBg.hidden = true
})
自动补全给了我completion: ((Bool) -> Void)?
,但不确定如何让它工作。我也尝试了尾部闭包,但得到了相同的错误:
! Could not find an overload for 'animateWithDuration that accepts the supplied arguments
Swift 3/4的更新:
// 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's answer below。
发布于 2014-06-06 06:48:14
animateWithDuration
中的完成参数接受一个块,该块接受一个布尔参数。在Swift中,就像在Obj-C块中一样,您必须指定闭包需要的参数:
UIView.animateWithDuration(0.2, animations: {
self.blurBg.alpha = 1
}, completion: {
(value: Bool) in
self.blurBg.hidden = true
})
这里最重要的部分是(value: Bool) in
。这告诉编译器这个闭包接受一个标记为'value‘的布尔值,并返回Void。
作为参考,如果您想要编写一个返回Bool的闭包,语法应该是
{(value: Bool) -> bool in
//your stuff
}
发布于 2014-06-06 06:40:06
完成是正确的,闭包必须接受一个Bool
参数:(Bool) -> ()
。试一试
UIView.animate(withDuration: 0.2, animations: {
self.blurBg.alpha = 1
}, completion: { finished in
self.blurBg.hidden = true
})
发布于 2017-01-16 02:03:26
有时,您希望将其抛入一个变量中,以根据情况以不同的方式进行动画。为此,您需要
let completionBlock : (Bool) -> () = { _ in
}
或者你可以使用同样冗长的:
let completionBlock = { (_:Bool) in
}
但在任何情况下,您都必须在某个地方指出Bool
。
https://stackoverflow.com/questions/24071334
复制相似问题