2016-09-19 69 views
2
fileprivate func hideViewWithAnimation() { 

    UIView.animate(withDuration: 0.3, animations: { [weak self] 
     if self == nil { 
      return 
     } 

     self!.view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) 

     self!.constraintContainerViewBottom.constant = -Constants.screenHeight() 
     self!.constraintContainerViewTop.constant = Constants.screenHeight() 
     self!.view.layoutIfNeeded() 

    }, completion: { (isCompleted) in 
     self.navigationController?.dismiss(animated: false, completion: nil) 
    }) 
} 

有一個錯誤顯示[weak self]要求使用','分隔它。我在做什麼錯[weak self]給出以下代碼的錯誤:預期','分隔符

+2

''[weak self] in',你沒有'in' – Tj3n

回答

1

正如Tj3n說,當你使用[weak self]語法,你需要的in關鍵字,例如

UIView.animate(withDuration: 0.3) { [weak self] in 
    self?.view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) 

    ... 
} 

但你不要在動畫塊需要[weak self]可言,因爲動畫塊不保留的強引用self爲動畫的持續時間。沒有強烈的參考週期可以突破。所以我建議完全刪除[weak self]

而且,如果你想知道,你並不需要擔心強引用在completion塊,或者說,因爲當視圖被駁回,動畫正在被取消,completion塊立即用false稱爲爲布爾參數。

+0

謝謝。我後來發現,我們不需要[弱自我]製作動畫塊。「 –

-3
private func hideViewWithAnimation() { 

    weak var weakSelf = self 

    if weakSelf != nil { 
     UIView.animateWithDuration(0.3, animations: { 

      self!.view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) 

      self!.constraintContainerViewBottom.constant = -Constants.screenHeight() 
      self!.constraintContainerViewTop.constant = Constants.screenHeight() 
      self!.view.layoutIfNeeded() 

     }) { (isCompleted) in 
      self.navigationController?.dismiss(animated: false, completion: nil) 

     } 

    } 
}