动画不能在swift中工作

时间:2017-10-09 18:46:49

标签: ios swift uicollectionview

我在键盘输入视图中有一个按钮和一个集合视图(水平)。使用自动布局。默认情况下,使用“领先约束”设置为-50隐藏该按钮。当用户开始使用集合视图且集合视图的 contentOffset.x 大于80时,将显示该按钮。代码工作正常,但动画无效。

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)
        }
    }
}

2 个答案:

答案 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)
    }
}}

答案 1 :(得分:0)

首先,你不应该改变动画块内的约束。其次,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) } } } 方法被调用了很多次,你应该在其中调用动画代码设置一些限制。尝试这样的事情:

{{1}}