【问题标题】:swift 4 Constraint animation does not work correctlyswift 4 约束动画无法正常工作
【发布时间】:2018-06-04 09:19:11
【问题描述】:

我有自定义的点击栏,其中包含 4 个项目的 collectionView。我有一个白色视图,它指示选定的项目并在点击另一个 collectionView 项目时更改其位置(带有动画)。带约束的白色视图定位,我将左锚约束更改为动画

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let x = CGFloat(indexPath.item) * frame.width / 4
        self.horizontalBarLeftAnchorConstraint?.constant = x
        UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
            self.layoutIfNeeded()
        }, completion: nil)
    }

动画无法正常工作,一开始它会跳到当前位置前 1 个宽度(白色视图)的位置,并从该位置开始动画

我发现了问题 // 我对滚动集合视图的响应有另一个这个约束的动画,在这里我有产生这种跳跃的双重动画,我删除了第二个动画,现在一切看起来都很好

【问题讨论】:

    标签: ios animation constraints swift4


    【解决方案1】:

    您没有设置任何动画条件,也许我不明白您的问题。但你应该使用:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        // BEFORE ANIMATION CONTEXT
    
        UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
    
        // ANIMATION TILL END CONTEXT
        self.layoutIfNeeded
    
        }, completion: {
    
        // AFTER ANIMATION CONTEXT
    
        })
    }
    

    【讨论】:

    • self.horizo​​​​ntalBarLeftAnchorConstraint 属性是在此函数之前设置的,我在此函数中更改了它的值,然后要求在动画块中重绘视图
    • 动画上下文中的值应该不同,块中的值不应该是相同的 x 动画
    【解决方案2】:
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
    
           let x = CGFloat(indexPath.item) * frame.width / 4
           self.horizontalBarLeftAnchorConstraint?.constant = x
            self.layoutIfNeeded()
        }, completion: nil)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2023-01-16
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多