繁体   English   中英

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

[英]Pass function to completion handler

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

在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'传递给需要@转义闭包的函数

}, 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     
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM