UIView 动画立即完成,不考虑持续时间或延迟

Mou*_*heg 1 uiviewanimation ios swift

我在为我的视图的 layoutConstraints 之一设置动画时遇到了一些困难:

UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
                self.topLayoutConstraint?.constant = self.currentYPosition
                self.layoutIfNeeded()
                }, completion: nil)
Run Code Online (Sandbox Code Playgroud)

无论我使用什么持续时间或延迟,动画都会立即完成(我的视图从以前的位置跳转到新的位置)。

我已经检查了所有值,它们是正确的。我还检查过并调用了动画和完成。

有任何想法吗 ?

编辑:

@objc private func viewDragged(_ recognizer: UIPanGestureRecognizer) {

        let location = recognizer.location(in: self.superview)

        switch recognizer.state {
        case .ended:

            if (recognizer.direction == .Down) {            // Collapsing the slide panel

                currentYPosition = parentViewHeight - minimumVisibleHeight - statusBarHeight - navBarHeight
            }
            else if (recognizer.direction == .Up) {       // Expanding the slide panel

                // Substracting `minimumVisibleHeight` so that the dragable part is hidden behind the navigation bar
                currentYPosition = -minimumVisibleHeight
            }

            self.topLayoutConstraint?.constant = self.currentYPosition
            UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
                self.layoutIfNeeded()
                }, completion: nil)
            break
        case .began:
            HomeSlidePanelContainerView.draggingPreviousPosition = location.y
        default:
            self.layoutIfNeeded()

            if (location.y < (parentViewHeight - minimumVisibleHeight - statusBarHeight - navBarHeight)
                || location.y > (statusBarHeight + navBarHeight)) {

                currentYPosition -= HomeSlidePanelContainerView.draggingPreviousPosition - location.y
                topLayoutConstraint?.constant = currentYPosition
                self.layoutIfNeeded()
            }
            HomeSlidePanelContainerView.draggingPreviousPosition = location.y
            break
        }

    }
Run Code Online (Sandbox Code Playgroud)

Mou*_*heg 5

我设法找到了解决方案。这可能对其他人有帮助,所以我正在回答我自己的问题。

我正在做的是这样的:

self.topLayoutConstraint?.constant = self.currentYPosition

UIView.animate(withDuration: 1, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {               
                self.layoutIfNeeded()
}, completion: nil)
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我改变了一个值,topLayoutConstraint即是一种约束上self这是一个UIView

然后我试图通过调用self.layoutIfNeeded动画闭包来为该更改设置动画。

这里的事情是layoutIfNeeded()适用于子视图而不是视图本身。所以在我的情况下,我试图为self的子视图的布局而不是self它本身设置动画。

改变self.layoutIfNeeded()self.superview?.layoutIfNeeded(),瞧!