代码之家  ›  专栏  ›  技术社区  ›  Turnip Moushumi Ahmed

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

  •  2
  • Turnip Moushumi Ahmed  · 技术社区  · 7 年前

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

    在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) -&燃气轮机;无效)?”

    }, completion: { myCompletionHandler() })
    

    闭包使用非转义参数“myCompletionHandler”可能允许它 逃跑

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

    myCompletionHandler .animate 完成处理程序?

    3 回复  |  直到 7 年前
        1
  •  8
  •   Dávid Pásztor    7 年前

    如果您想将自己的闭包作为输入参数传递给 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
    })
    
        2
  •  0
  •   Damien    7 年前

    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()
            })
        }
    }
    
        3
  •  0
  •   Arpit Jain Vivek Sharma    7 年前
    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     
    }