ios - 动画约束相对于另一个约束

标签 ios swift animation constraints

我设置了一个动画,以在打开另一个开关/标签时隐藏一个开关/标签。同时刚刚打开的开关向上移动。通过简单的解释,这非常有效 here

但是,当我尝试在关闭后将开关/标签向下移动时,它没有移动。另一个开关重新出现正常,但顶部约束更改未触发。

我对这种类型的设置和以编程方式制作动画还比较陌生,在花了一个小时之后我被难住了。是因为我正在为相对于另一个约束的顶部约束设置动画吗?如果第一次就有效,那又有什么关系呢?即使隐藏开关的 alpha 设置为零,它的框架仍然存在,对吧?还是我愚蠢地做了一些简单的事情?

// Works Perfectly!

func hideVeg() {

    self.view.layoutIfNeeded()

    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 0
        self.vegetarianLabel.alpha = 0
        self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: -30).isActive = true
        self.view.layoutIfNeeded()
    })
}

// Showing the label and switch works, but the topAnchor constraint never changes!

func showVeg() {

    self.view.layoutIfNeeded()

    UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseIn], animations: {
        self.vegetarianSwitch.alpha = 1
        self.vegetarianLabel.alpha = 1

        // This is the constraint that doesn't change.
        // This is exactly what it was set to before the other hideVeg() runs.
        self.veganSwitch.topAnchor.constraint(equalTo: self.vegetarianSwitch.bottomAnchor, constant: 40).isActive = true
        self.view.layoutIfNeeded()
    })
}

最佳答案

这里的问题是您没有修改约束,而是实际上为每个动画创建新的约束。相反,您想要做的只是创建一次约束(您可以在代码中或在 Interface Builder 中进行,然后拖动并导出)。然后,您只需更改动画 block 中现有约束的 .constant 字段即可。

关于ios - 动画约束相对于另一个约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127297/

相关文章:

html - 从 Documents 目录在 UIWebview 中打开时,ios-css 和 js 无法在 html 文件中链接

ios - 是否可以在 Swift 中重载 += 运算符?

iOS自定义TableViewCell类 subview 返回null

swift - 如何在 Swift 中声明关键字变量

javascript - 使用 <a> 开始动画到动画所在的部分?

ios - 在 UIView/UIViewController 关系中定义委托(delegate)

objective-c - 如何在 iPhone 上制作 "iPod Wheel"类型的控件?

json - 如何在 Swift 中解析多级 json 结构?

ios - 反复连续动画 View

android - 具有大量位图的动画