将函数传递给完成处理程序

Pass function to completion handler

我有一个在视图上执行动画的函数。我想为此函数实现一个完成处理程序,该处理程序将在动画完成后调用。

在ViewController...

hudView.hide(animated: true, myCompletionHandler: {
    // Animation is complete
})

在 HudView 中 class...

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)

Passing non-escaping parameter 'myCompletionHandler' to function expecting an @escaping closure

}, completion: myCompletionHandler())

Cannot convert value of type 'Void' to expected argument type '((Bool) -> Void)?'

}, completion: { myCompletionHandler() })

Closure use of non-escaping parameter 'myCompletionHandler' may allow it to escape

作为一个 swift 新手,这些错误消息对我来说意义不大,我似乎找不到任何正确方法的例子。

myCompletionHandler 传递给 .animate 完成处理程序的正确方法是什么?

这是在 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()
        })
    }
}

如果您想将自己的闭包作为输入参数传递给 UIView.animate,您需要匹配闭包的类型,因此 myCompletionHandler 必须具有 [=14= 的类型], 就像 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
})
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     
}