我具有在视图上执行动画的函数。我想实现此功能的完成处理程序,该功能在动画完成后将被调用。
在ViewController中...
hudView.hide(animated: true, myCompletionHandler: {
// Animation is complete
})
在Hudview类中...
func hide(animated: Bool, myCompletionHandler: () -> Void) {
if animated {
transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self.alpha = 0
self.transform = CGAffineTransform.identity
}, completion: nil) // I want to run 'myCompletionHandler' in this completion handler
}
}
我已经尝试了许多事情,但找不到正确的语法:
}, completion: myCompletionHandler)
传递非排行参数" mycompletionhandler"以期望 @escaping闭合
}, completion: myCompletionHandler())
无法将'void'类型的值转换为预期参数类型'((bool) -> void)?'
}, completion: { myCompletionHandler() })
关闭非排放参数" mycompletionhandler"可能允许它 逃脱
作为迅速的新手,这些错误消息对我来说意义不大,我似乎找不到任何正确方法的示例。
将myCompletionHandler
传递给.animate
完成处理程序的正确方法是什么?
如果要将自己的封闭方式作为输入参数传递给UIView.animate
,则需要匹配封闭类型,因此myCompletionHandler
必须具有((Bool) -> ())?
的类型,就像completion
一样。
func hide(animated: Bool, myCompletionHandler: ((Bool) -> ())?) {
if animated {
transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self.alpha = 0
self.transform = CGAffineTransform.identity
}, completion: myCompletionHandler) // I want to run 'myCompletionHandler' in this completion handler
}
}
这就是您可以调用它的方式:
hudView.hide(animated: true, myCompletionHandler: { success in
//animation is complete
})
这是在uiview.animate中使用完成的方法:
func hide(animated: Bool, myCompletionHandler: () -> Void) {
if animated {
transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self.alpha = 0
self.transform = CGAffineTransform.identity
}, completion: { (success) in
myCompletionHandler()
})
}
}
You can create your function as,
func hide(_ animated:Bool, completionBlock:((Bool) -> Void)?){
}
And you can call it as,
self.hide(true) { (success) in
// callback here
}