如何正确更新自动版式约束,以使动画正确运行?

时间:2018-09-15 13:33:51

标签: ios swift autolayout constraints nslayoutconstraint

我参加自动版式聚会有点晚了,但是我已经尝试了几天,以了解为什么我的某些动画约束更改不能总是起作用,也不会在控制台中产生任何错误

基本上,我有:

  • 两个容器(顶部:红色,底部:橙色)
  • 底视图(橙色)中的子视图标签(黄色-表示“ Hello!”的标签)

从GIF中可以看到,调整顶部(红色)视图的高度会导致橙色容器变大...从而又使黄色视图随其伸展。但是,当红色视图变小时,我会得到一些奇怪的行为,黄色视图会立即缩小到大小,而不是跟随橙色视图的动画。

Unusual closing animation

我的约束配置如下:

topViewHeightConstraint = topView.heightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.7)
NSLayoutConstraint.activate([
  // Setup the top view
  topView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
  topView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
  topView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
  topViewHeightConstraint!,

  // Setup the constraits for the button inside the top view
  topViewButton.centerXAnchor.constraint(equalTo: topView.centerXAnchor),
  topViewButton.bottomAnchor.constraint(equalTo: topView.bottomAnchor, constant: -20),
  topViewButton.widthAnchor.constraint(equalToConstant: 100),
  topViewButton.heightAnchor.constraint(equalTo: topViewButton.widthAnchor, multiplier: 1.0),

  // Setup the bottom view
  bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
  bottomView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
  bottomView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
  bottomView.topAnchor.constraint(equalTo: topView.bottomAnchor),

  // Setup constraints for the label
  labelInsideBottomView.bottomAnchor.constraint(equalTo: self.bottomView.bottomAnchor),
  labelInsideBottomView.leadingAnchor.constraint(equalTo: self.bottomView.leadingAnchor),
  labelInsideBottomView.trailingAnchor.constraint(equalTo: self.bottomView.trailingAnchor),
  labelInsideBottomView.widthAnchor.constraint(equalTo: self.bottomView.widthAnchor),
  labelInsideBottomView.heightAnchor.constraint(equalTo: self.bottomView.heightAnchor)
])

然后,要调整容器视图的大小,我在调用以下代码(借助extension来替换乘数约束),我正在更新约束。

func moveViews() {
    if (topViewHeightConstraint.multiplier >= 0.69) {
        topViewHeightConstraint = topViewHeightConstraint.setMultiplier(multiplier: 0.5)
    } else {
        topViewHeightConstraint = topViewHeightConstraint.setMultiplier(multiplier: 0.7)
    }

    UIView.animate(withDuration: 1) {
        self.view.layoutIfNeeded()
    }
}

有人能看到我的设置有什么不寻常的地方吗,或提出一种无需怪异动画就可以实现这一目标的方法吗?

谢谢!

0 个答案:

没有答案
相关问题