UIView animateKeyframes无法与NSLayoutConstraints一起使用

时间:2018-11-16 14:15:35

标签: ios swift autolayout

我正在尝试通过减小UIView的宽度约束为UIView设置动画,但是在使用UIView.animateKeyFrames时效果不佳。这是我的代码:

    UIView.animateKeyframes(withDuration: 2.0, delay: 0, options: [.calculationModeCubic], animations: {
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1.0/2.0, animations: {
            self.titleLabel.alpha = 0.0 // works well
        })

       self.titleSquareHeightConstraint?.constant = 20 // previously 170
        UIView.addKeyframe(withRelativeStartTime: 1.0/2.0, relativeDuration: 1.0/2.0, animations: {
            self.titleSquare.layoutIfNeeded() // instantaneously jump to 20
        })

    }, completion:nil)

titleSquare的高度将立即从170跳到20。 注意:titleSquare是一个UIView 。另外,我曾经使用UIView.animate,下面的代码也可以正常工作:

    self.titleSquareHeightConstraint?.constant = 20
    UIView.animate(withDuration: 0.5,
                   delay: 0,
                   usingSpringWithDamping: 1,
                   initialSpringVelocity: 1,
                   options: .curveEaseIn,
                   animations: {

                    self.view.layoutIfNeeded() // Perfectly works

    },completion: nil)

我的UIView.animateKeyframes方法在做什么?看来我还没有完全了解它是如何工作的?

谢谢

1 个答案:

答案 0 :(得分:2)

不完全明显或直观,但是...

您要将视图告诉layoutIfNeeded()

    UIView.animateKeyframes(withDuration: 2.0, delay: 0, options: [.calculationModeCubic], animations: {

        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1.0/2.0, animations: {
            self.titleLabel.alpha = 0.0 // works well
        })

        self.titleSquareHeightConstraint.constant = 20 // previously 170

        UIView.addKeyframe(withRelativeStartTime: 1.0/2.0, relativeDuration: 1.0/2.0, animations: {

            // tell self.view to layout, not the titleSquare view
            self.view.layoutIfNeeded()

        })

    }, completion:nil)