动画不能在swift中工作

问题描述:

我在键盘输入视图中有一个按钮和一个集合视图(水平)。自动布局被使用。 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 –

首先,你不应该改变你的动画块内的约束。其次,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

谢谢..它的工作原理 –

通过更新动画块外部的常量,尝试以下方法。它会做动画效果的更新。

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

更改了代码。不工作 –