UIView.animate 没有在一个函数上设置动画

UIView.animate not animating on one function

我有两个函数可以为 UIView 设置动画。一个用于显示它,另一个用于驳回该视图。奇怪的是显示视图的动画有效,但关闭的动画无效。

show() 在视图添加为子视图后立即被调用。

func show() {
    self.viewContainer.frame.origin.y = self.view.frame.height + 500
    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
        self.viewContainer.frame.origin.y = self.view.frame.height
    }, completion: nil)
}

虽然 dismiss() 是使用 UITapGestureRecognizer 或按下按钮调用的。

func dismiss() {
    self.overlay.isHidden = true
    self.viewContainer.frame.origin.y = self.view.frame.height
    UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
        self.viewContainer.frame.origin.y = self.view.frame.height + 500
    }) { (_) in
        self.view.removeFromSuperview()
    }
}

这里似乎有什么问题?

你可以试试这个

func dismiss() {
 UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
     self.viewContainer.frame.origin.y = self.view.frame.height + 500
     self.overlay.isHidden = true
 }, completion: nil)
}

删除 dissmis() 中的这段代码

self.viewContainer.frame.origin.y = self.view.frame.height

你为什么要在 show() 中这样做?

self.viewContainer.frame.origin.y = self.view.frame.height

如果你想展示在中心使用

self.viewContainer.center.y = self.view.center.y

通过为视图的底部约束而不是其框架设置动画来修复它。

UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: {
    self.viewBottomConstraint.constant = -500
    self.view.layoutIfNeeded()
}) { (_) in
    self.view.removeFromSuperview()
}

得到提示: