当应用程序进入后台时按钮跳转位置

Button jumps position when app enters background

我有一个小按钮来显示和隐藏 UI 元素。当我按下主页按钮离开应用程序然后返回它时,按钮跳转到其原始位置,而不是它被动画化的新位置。

期望的操作是当用户离开并返回应用程序时它会保留在用户离开的位置。

@IBAction func hideChartTapped(_ sender: Any) {
    let delay = 0.3
    if chart.isHidden {
        self.chart.isHidden = false
        UIView.animate(withDuration: delay, animations: {
            self.hideChart.center.y = (self.hideChart.center.y - self.chart.bounds.height)
            self.chart.center.y = (self.chart.center.y - self.chart.bounds.height)
        }, completion: nil)
    } else {
        UIView.animate(withDuration: delay, animations: {
            self.hideChart.center.y = (self.hideChart.center.y + self.chart.bounds.height)
            self.chart.center.y = (self.chart.center.y + self.chart.bounds.height)
            self.hideChart.setNeedsDisplay()
        }, completion: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
            self.chart.isHidden = true
        })
    }
}

这是我用来隐藏和显示图表以及移动按钮的代码。按钮和图表的默认位置设置在 main.Storyboard.

我明白了。我也没有更新约束。我仍在为中心运动设置动画,但在动画之后,我正在像这样重置约束:

@IBAction func hideChartTapped(_ sender: Any) {
    let delay = 0.3
    if chart.isHidden {
        self.chart.isHidden = false
        UIView.animateKeyframes(withDuration: delay, delay: 0, options: [], animations: {
            self.hideChart.center.y = (self.hideChart.center.y - self.chart.bounds.height)
            self.chart.center.y = (self.chart.center.y - self.chart.bounds.height)
        }, completion: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
            self.hideChartBottomConstraint.constant = 0
            self.hideChart.layoutIfNeeded()
        })
    } else {
        UIView.animateKeyframes(withDuration: delay, delay: 0, options: [], animations: {
            self.hideChart.center.y = (self.hideChart.center.y + self.chart.bounds.height)
            self.chart.center.y = (self.chart.center.y + self.chart.bounds.height)
        }, completion: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
            self.hideChartBottomConstraint.constant = self.chart.bounds.height
            self.hideChart.layoutIfNeeded()
            self.chart.isHidden = true
        })
    }
}