2017-09-26 66 views
0

我有一個在視圖上執行動畫的函數。我想爲這個函數實現一個完成處理程序,它將在動畫完成後調用。將函數傳遞給完成處理程序

在視圖控制器...

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) 

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

謝謝大衛。這很好。 – 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

我已經更新了我的答案,這將工作。 –

相關問題