2017-10-09 68 views
0

我在鍵盤輸入視圖中有一個按鈕和一個集合視圖(水平)。自動佈局被使用。 Leading Constraint設置爲-50,該按鈕默認隱藏。當用戶開始使用集合視圖並且contentOffset.x的集合視圖大於80時,該按鈕將顯示。代碼工作正常,但動畫不起作用。動畫不能在swift中工作

extension ViewController: UIScrollViewDelegate { 
    func scrollViewDidScroll(_ scrollView: UIScrollView) { 
     if self.collectionView.contentOffset.x > 80 { 
      UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: { 
       self.sideButtonLeadingConstraint.constant = 0 
       self.view.layoutIfNeeded() 
      }, completion: nil) 
     } else { 
      UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: { 
       self.sideButtonLeadingConstraint.constant = -50 
       self.view.layoutIfNeeded() 
      }, completion: nil) 
     } 
    } 
} 
+0

項目鏈接https://drive.google.com/file/d/0B5UHWsK1E6dSTFh4ZDJxMmxpYUE/view?usp=sharing –

回答

0

首先,你不應該改變你的動畫塊內的約束。其次,scrollViewDidScroll方法被調用了很多次,您應該爲調用其中的動畫代碼設置一些限制。嘗試是這樣的:

extension ViewController: UIScrollViewDelegate { 
    func scrollViewDidScroll(_ scrollView: UIScrollView) { 
     let needsShow = collectionView.contentOffset.x > 80 && sideButtonLeadingConstraint.constant != 0 
     let needsHide = collectionView.contentOffset.x <= 80 && sideButtonLeadingConstraint.constant != -50 

     if needsShow { 
      sideButtonLeadingConstraint.constant = 0     
     } else if needsHide { 
      sideButtonLeadingConstraint.constant = -50 
     } 

     if needsShow || needsHide { 
      UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: { 
       self.view.layoutIfNeeded() 
      }, completion: nil) 
     } 
    } 
} 
+0

無法使用https://drive.google.com/file/d/0B5UHWsK1E6dSTFh4ZDJxMmxpYUE/view?usp=sharing –

+0

您應該致電' self.photoView.layoutIfNeeded()'而不是'self.view.layoutIfNeeded()'在你的情況 –

+0

謝謝..它的工作原理 –

1

通過更新動畫塊外部的常量,嘗試以下方法。它會做動畫效果的更新。

extension ViewController: UIScrollViewDelegate { 
func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    if self.collectionView.contentOffset.x > 80 { 
     self.sideButtonLeadingConstraint.constant = 0 
     UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: { 
      self.view.layoutIfNeeded() 
     }, completion: nil) 
    } 
    else { 
     self.sideButtonLeadingConstraint.constant = -50 
     UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: { 
      self.view.layoutIfNeeded() 
     }, completion: nil) 
    } 
}} 
+0

仍然沒有工作 –

+0

嘗試UIView.animate(withDuration:1,動畫: {self.view.layoutIfNeeded()})而不是特定的動畫類型。 – Bharath

+0

更改了代碼。不工作 –