2017-09-26 6 views
0

私はビューに対してアニメーションを実行する関数を持っています。アニメーションが完了した後に呼び出されるこの関数の補完ハンドラを実装したいと思います。 ViewControllerで完了ハンドラに関数を渡す

... HudViewクラスで

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

...

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

これらのエラーメッセージは、私には非常に多くを意味するものではありませんし、私はこれを行うには正しい方法のいずれかの例を見つけるように見える傾けます。

myCompletionHandler.animate完了ハンドラに渡す正しい方法は何ですか?

答えて

2

あなたは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 
}) 
+1

Davidありがとう。それは素晴らしい作品です。 – Turnip

0

これは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() 
     }) 
    } 
} 
+0

おかげダミアン。しかし、これはコンパイラエラーをスローします: '非エスケープパラメータのクローズの使用 'myCompletionHandler'がエスケープできるようにする' – Turnip

0
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  
} 
+0

これは私に: '@escaping属性は関数型にのみ適用されます' – Turnip

+0

これは動作する私の答えを更新しました。 –

関連する問題